diff --git a/.DS_Store b/.DS_Store
index bb9687b..a5ea54c 100644
Binary files a/.DS_Store and b/.DS_Store differ
diff --git a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate
index 554ba12..59acbc9 100644
Binary files a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate and b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate differ
diff --git a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
index 07464a5..70e71b3 100644
--- a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
+++ b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
@@ -10,11 +10,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/EtsyRESTAPIManager.swift"
- timestampString = "490466193.9234"
+ timestampString = "491361523.935232"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "224"
- endingLineNumber = "224"
+ startingLineNumber = "231"
+ endingLineNumber = "231"
landmarkName = "authorizeApp(_:)"
landmarkType = "5">
@@ -26,141 +26,13 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/EtsyRESTAPIManager.swift"
- timestampString = "490466544.006941"
+ timestampString = "491361523.935232"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "227"
- endingLineNumber = "227"
+ startingLineNumber = "234"
+ endingLineNumber = "234"
landmarkName = "authorizeApp(_:)"
landmarkType = "5">
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -182,15 +54,15 @@
@@ -202,11 +74,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/EtsyRESTAPIManager.swift"
- timestampString = "490830825.959087"
+ timestampString = "491361523.935232"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "396"
- endingLineNumber = "396"
+ startingLineNumber = "403"
+ endingLineNumber = "403"
landmarkName = "sendGETRequest(_:onCompletion:)"
landmarkType = "5">
@@ -218,11 +90,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/ListingPreviewViewController.swift"
- timestampString = "490832217.159988"
+ timestampString = "491357363.968778"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "250"
- endingLineNumber = "250"
+ startingLineNumber = "260"
+ endingLineNumber = "260"
landmarkName = "publishItem(_:)"
landmarkType = "5">
@@ -234,43 +106,187 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/ListingPreviewViewController.swift"
- timestampString = "490832219.521989"
+ timestampString = "491396358.880255"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "262"
- endingLineNumber = "262"
+ startingLineNumber = "286"
+ endingLineNumber = "286"
landmarkName = "publishItem(_:)"
landmarkType = "5">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ startingLineNumber = "216"
+ endingLineNumber = "216"
+ offsetFromSymbolStart = "4169">
+ startingLineNumber = "219"
+ endingLineNumber = "219"
+ offsetFromSymbolStart = "43">
@@ -282,12 +298,284 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Vendoo/EtsyRESTAPIManager.swift"
- timestampString = "490834455.083173"
+ timestampString = "491361667.580641"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
- startingLineNumber = "448"
- endingLineNumber = "448"
- landmarkName = "convertStringToDictionary(_:)"
+ startingLineNumber = "219"
+ endingLineNumber = "219"
+ landmarkName = "authorizeApp(_:)"
+ landmarkType = "5">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Vendoo/.DS_Store b/Vendoo/.DS_Store
index cf11e23..1b9a41c 100644
Binary files a/Vendoo/.DS_Store and b/Vendoo/.DS_Store differ
diff --git a/Vendoo/CategoriesTableViewController.swift b/Vendoo/CategoriesTableViewController.swift
index a6d192f..f654cea 100644
--- a/Vendoo/CategoriesTableViewController.swift
+++ b/Vendoo/CategoriesTableViewController.swift
@@ -17,7 +17,6 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
private var ebayManager: EbayWebServiceManager! = EbayWebServiceManager()
private var selectedCategory: String!
- //@TODO: replace with etsy categories and make a custom cell to contain a collection view of images for ebay/etsy approriatecolumns relevant to the category
private var categories = ["Accessories",
"Art",
"Bath & Beauty",
diff --git a/Vendoo/EtsyRESTAPIManager.swift b/Vendoo/EtsyRESTAPIManager.swift
index db70192..5efd292 100644
--- a/Vendoo/EtsyRESTAPIManager.swift
+++ b/Vendoo/EtsyRESTAPIManager.swift
@@ -15,7 +15,7 @@ import Locksmith
import AFNetworking
-typealias ServiceResponse = (JSON, NSError?) -> Void
+typealias ServiceResponse = (AnyObject?, NSError?) -> Void
class EtsyRESTAPIManager: NSObject {
@@ -213,6 +213,13 @@ extension EtsyRESTAPIManager {
EtsyRESTAPIManager.settingsDictionary["userID"] = dict2[0]["login_name"]!
NSUserDefaults.standardUserDefaults().setObject(EtsyRESTAPIManager.settingsDictionary, forKey: "etsySettings")
+ self.sendGETRequest("/shops/__SELF__/payment_templates", onCompletion: {
+ (data, error) -> Void in
+
+ self.sendGETRequest("/users/__SELF__/shipping/templates", onCompletion: nil)
+
+ })
+
}
, failure: { error in
print(error)
@@ -392,48 +399,317 @@ extension EtsyRESTAPIManager {
}
//sends the pregenerated url as a request to api service
- func sendGETRequest(request: String, onCompletion: ServiceResponse) {
- let request = NSMutableURLRequest(URL: NSURL(string: request)!)
+ func sendGETRequest(request: String, onCompletion: ServiceResponse?) {
+ /* let request = NSMutableURLRequest(URL: NSURL(string: request)!)
+
+ let session = NSURLSession.sharedSession()
+
+ let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
+ if let jsonData = data {
+ let json:JSON = JSON(data: jsonData)
+ onCompletion(json, error)
+ } else {
+ onCompletion(nil, error)
+ }
+ })
+ task.resume()*/
- let session = NSURLSession.sharedSession()
-
- let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
- if let jsonData = data {
- let json:JSON = JSON(data: jsonData)
- onCompletion(json, error)
- } else {
- onCompletion(nil, error)
+ self.oauthswift.client.get(self.baseURL + request,
+ success: {
+ (data, response) -> Void in
+ let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ switch (request) {
+ case "/shops/__SELF__/payment_templates" :
+
+ if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) {
+ //@TODO: Put payment template parameters in function call
+ self.oauthswift.client.post(self.baseURL + "/shops/__SELF__/payment_templates",
+ parameters: [
+ "shop_id":"__SELF__",
+ ],
+ headers: nil,
+ success: {
+ (data, response) -> Void in
+ let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ onCompletion!(nil,nil)
+
+ },
+ failure: {
+ (error) -> Void in
+ print(error)
+ }
+ )
+ }
+ break
+ case "/users/__SELF__/shipping/templates" :
+ var dict2 = (dict!["results"] as! [[String : AnyObject]])
+
+ if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) {
+ //@TODO: Put payment template parameters in function call
+ self.oauthswift.client.post(self.baseURL + "/shipping/templates",
+ parameters: [
+ "title":"vendoo_default",
+ "origin_country_id":209,
+ "primary_cost":2.00,
+ "secondary_cost":1.00
+ ],
+ headers: nil,
+ success: {
+ (data, response) -> Void in
+ let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ },
+ failure: {
+ (error) -> Void in
+ print(error)
+ }
+ )
+ }else {
+ EtsyRESTAPIManager.settingsDictionary["shipping_template_id"] = dict2[0]["shipping_template_id"]!
+
+ NSUserDefaults.standardUserDefaults().setObject(EtsyRESTAPIManager.settingsDictionary, forKey: "etsySettings")
+ }
+
+ break
+ default:
+ break
+ }
+
+ },
+ failure: {
+ (error) -> Void in
+ print(error)
+
}
- })
- task.resume()
+ )
}
//sends the pregenerated url as a request to api service
- func sendPOSTRequest(request: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
- let request = NSMutableURLRequest(URL: NSURL(string: request)!)
+ func sendPOSTRequest(request: String, var body: [String: AnyObject], onCompletion: ServiceResponse?) {
- // Set the method to POST
- request.HTTPMethod = "POST"
+ /* let request = NSMutableURLRequest(URL: NSURL(string: request)!)
+
+ // Set the method to POST
+ request.HTTPMethod = "POST"
+
+ do {
+ // Set the POST body for the request
+ let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
+ request.HTTPBody = jsonBody
+ let session = NSURLSession.sharedSession()
+
+ let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
+ if let jsonData = data {
+ let json:JSON = JSON(data: jsonData)
+ onCompletion(json, nil)
+ } else {
+ onCompletion(nil, error)
+ }
+ })
+ task.resume()
+ } catch {
+ // Create your personal error
+ onCompletion(nil, nil)
+ }*/
- do {
- // Set the POST body for the request
- let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
- request.HTTPBody = jsonBody
- let session = NSURLSession.sharedSession()
+ if(request.containsString("listings/") && request.containsString("/images")){
- let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
- if let jsonData = data {
- let json:JSON = JSON(data: jsonData)
- onCompletion(json, nil)
- } else {
- onCompletion(nil, error)
+ let url = NSURL(string: self.baseURL + request)!
+ let requested = NSMutableURLRequest(URL: url)
+ requested.HTTPMethod = "POST"
+ let boundary = "Boundary-\(NSUUID().UUIDString)"
+ /*var headers = oauthswift.client.credential.makeHeaders(url, method: OAuthSwiftHTTPRequest.Method.POST, parameters: ["Content-Type":"multipart/form-dataheader"]) // here with create the authentification headers
+ requested.addValue(self.apiKey, forHTTPHeaderField: "Authorization" )
+
+ //define the multipart request type
+ requested.addValue("\((body["image"] as! NSData).length)", forHTTPHeaderField: "Content-Length")
+ requested.addValue("bytes", forHTTPHeaderField: "Content-Transfer-Encoding")
+ requested.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
+ //requested.addValue(self.apiKey, forHTTPHeaderField: "API-KEY")
+ requested.HTTPBody = self.oauthswift.client.multiPartBodyFromParams(body, boundary: boundary)
+ /*let body1 = NSMutableData()
+
+ let fname = "main.jpg"
+ let mimetype = "image/jpg"
+
+ //define the data post parameter
+
+ body1.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+ body1.appendData("Content-Disposition:form-data; name=\"listing_id\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+ body1.appendData("\(body["listing_id"] as! Int)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+
+
+
+ body1.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+ body1.appendData("Content-Disposition:form-data; name=\"image\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+ body1.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+ body1.appendData((body["image"] as! NSData))
+ body1.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+
+
+ body1.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
+
+
+
+ requested.HTTPBody = body1*/
+
+ let session = NSURLSession.sharedSession()
+
+
+ let task = session.dataTaskWithRequest(requested) { data, response, error in
+ if nil != error {
+ // something went wrong
+ print(error)
+
+ onCompletion!(nil,nil)
+ switch (request) {
+
+ default:
+ break
+ }
+ }
+ else {
+ let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ onCompletion!(nil, nil)
+ switch (request) {
+
+ default:
+ break
+ }
+ }
+ }
+ task.resume()*/
+ /*
+ //var headers = oauthswift.client.credential.makeHeaders(url, method: OAuthSwiftHTTPRequest.Method.POST, parameters: ["Content-Type":"multipart/form-dataheader"]) // here with create the authentification headers
+ // here add additional headers "Content-type", etc..
+ requested.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
+ requested.addValue("\((body["image"] as! NSData).length)", forHTTPHeaderField: "Content-Length")
+ requested.addValue("bytes", forHTTPHeaderField: "Content-Transfer-Encoding")
+ //requested.addValue("form-data; name='Main Image'; filename='mainImage.jpg'", forHTTPHeaderField: "Content-Disposition")
+ requested.HTTPBody = self.oauthswift.client.multiPartBodyFromParams(body, boundary: "-XXX--")
+
+ let session = NSURLSession.sharedSession()
+ let task = session.dataTaskWithRequest(requested) { data, response, error in
+ if nil != error {
+ // something went wrong
+ print(error)
+
+ onCompletion!(nil,nil)
+ switch (request) {
+
+ default:
+ break
+ }
+ }
+ else {
+ let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ onCompletion!(nil, nil)
+ switch (request) {
+
+ default:
+ break
+ }
+ }
+ }
+ task.resume()
+ */
+ //body["oauth_verifier"] = (self.oauthswift.client.credential.oauth_verifier)
+ //@FIXME: multipart post request is returning with oauth signature invalid for uploading image in etsy
+ self.oauthswift.client.postMultiPartRequest(self.baseURL + request, method: OAuthSwiftHTTPRequest.Method.POST, parameters: body, success: {
+ (data, response) -> Void in
+ let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ onCompletion!(nil, nil)
+ switch (request) {
+
+ default:
+ break
}
- })
- task.resume()
- } catch {
- // Create your personal error
- onCompletion(nil, nil)
+
+
+ },
+ failure: {
+ (error) -> Void in
+ print(error)
+
+ onCompletion!(nil,nil)
+ switch (request) {
+
+ default:
+ break
+ }
+
+ }
+ )
+ }else {
+ self.oauthswift.client.post(self.baseURL + request, parameters: body, headers: nil,
+ success: {
+ (data, response) -> Void in
+ let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
+ let dict = self.convertStringToDictionary(dataString! as String)
+ print(dict)
+ print(response)
+
+ switch (request) {
+ case "/shipping/templates":
+
+ break
+ case "/listings":
+ var dict2 = (dict!["results"] as! [[String : AnyObject]])
+ print(((dict2[0]["listing_id"])!))
+ onCompletion!(dict2, nil)
+ break
+ default:
+ break
+ }
+
+
+ },
+ failure: {
+ (error) -> Void in
+ print(error)
+ switch (request) {
+ case "/shipping/templates":
+
+ break
+ case "/listings":
+ print(error.userInfo["Response-Body"])
+ if((error.userInfo["Response-Body"]!.isEqualToString("price is below listing fee."))) {
+ //@TODO: add alert to let user know that the price they have given is too low for etsy
+
+ }
+ break
+ default:
+ break
+ }
+
+ }
+ )
}
+
+
}
}
diff --git a/Vendoo/FacebookGraphAPIManager.swift b/Vendoo/FacebookGraphAPIManager.swift
index 55a3df7..c196110 100644
--- a/Vendoo/FacebookGraphAPIManager.swift
+++ b/Vendoo/FacebookGraphAPIManager.swift
@@ -21,13 +21,13 @@ protocol FacebookGraphAPIManagerDelegate {
}
/*
- NOTES:
+ NOTE:
I am able to authorize application for use with facebook and deauthorize it while showing the toggle button switching back and forth, but during the last step of the process, for some reason NSUserDefault key for fbauthorized is not being called, in response handler, may need to run in a different thread
NEED to figure out how to post picture and text as the same timeline post current can only upload item title, price and description.
*/
class FacebookGraphAPIManager: NSObject {
-
+
//API Manager class variables
//----------------------------------------------//
static let sharedInstance = FacebookGraphAPIManager()
@@ -59,7 +59,7 @@ class FacebookGraphAPIManager: NSObject {
}
}
-
+
}
@@ -136,7 +136,7 @@ extension FacebookGraphAPIManager {
return self.makeDELETIONResquest("me/permissions", params: nil)
}
-
+
}
//MARK: - request methods(GET, POST, DELETE, SHARE)
@@ -153,23 +153,23 @@ extension FacebookGraphAPIManager {
//when making request make sure path starts with '/'
func makeGETRequest(requestPath: String!, params: [NSObject: AnyObject]!) -> Bool{
-
+
let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: requestPath, parameters: params)
var boolResult: Bool = false
dispatch_async(dispatch_get_main_queue(), {
- graphRequest.startWithCompletionHandler({
- (id, result, error) -> Void in
-
- print(result)
-
-
-
-
- })
+ graphRequest.startWithCompletionHandler({
+ (id, result, error) -> Void in
+
+ print(result)
+
+
+
+
+ })
})
return boolResult
-
+
}
//used to post to users timeline, path must start with '/'
@@ -177,28 +177,28 @@ extension FacebookGraphAPIManager {
/*if(FBSDKAccessToken.currentAccessToken() != nil && FBSDKAccessToken.currentAccessToken().hasGranted("pubish_actions")){*/
+
+ let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: requestPath, parameters: params, HTTPMethod: "POST")
+ graphRequest.startWithCompletionHandler({
+ (id, result, error) -> Void in
- let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: requestPath, parameters: params, HTTPMethod: "POST")
- graphRequest.startWithCompletionHandler({
- (id, result, error) -> Void in
+
+ if(error == nil){
+ print(result["id"])
+ self.delegate?.listingUploadedFB((result["id"] as? String)!)
+ print(result)
- if(error == nil){
-
- print(result["id"])
- self.delegate?.listingUploadedFB((result["id"] as? String)!)
- print(result)
-
- }
- else{
-
- }
- //save id in firebase so retrieval can be done later
- })
+ }
+ else{
+
+ }
+ //save id in firebase so retrieval can be done later
+ })
//}
/*else{
- print("must reauthenticate facebook")
- }*/
+ print("must reauthenticate facebook")
+ }*/
}
@@ -232,5 +232,5 @@ extension FacebookGraphAPIManager {
return boolResult
}
-
+
}
diff --git a/Vendoo/HomeViewController.swift b/Vendoo/HomeViewController.swift
index 7cb02ea..e5ceaaf 100644
--- a/Vendoo/HomeViewController.swift
+++ b/Vendoo/HomeViewController.swift
@@ -34,16 +34,6 @@ class HomeViewController: UITabBarController {
for (key, values) in listingDict! {
let serviceGroup: dispatch_group_t = dispatch_group_create()
- //@TODO: this is now getting all images but it is only displaying the last retrieved listings's set of images
- /*dispatch_group_notify(countGroup, dispatch_get_main_queue(), {
- print(HomeViewController.completionCount)
- HomeViewController.completionCount += 1
- if(HomeViewController.completionCount == 4){
-
- HomeViewController.completionCount = 0
- dispatch_group_leave(serviceGroup)
- }
- })*/
self.firebaseManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
let databaseDict = snapshot.value as! [String : AnyObject]
@@ -52,7 +42,6 @@ class HomeViewController: UITabBarController {
let mainListingImage = storageRef.child("images/\(key)/main.jpg")
- //@TODO: add in logic to programmatically retrieve each stored image and store in listing object as a way to display each image
dispatch_group_enter(serviceGroup)
mainListingImage.dataWithMaxSize(10 * 1024 * 1024, completion: {
(dataMain, error) -> Void in
diff --git a/Vendoo/ListingPreviewViewController.swift b/Vendoo/ListingPreviewViewController.swift
index 1462065..aa738b0 100644
--- a/Vendoo/ListingPreviewViewController.swift
+++ b/Vendoo/ListingPreviewViewController.swift
@@ -14,7 +14,7 @@
*/
import UIKit
-
+//@TODO: Need to make multiple images work for etsy and facebook and need to implement multiple images saving to firebase
class ListingPreviewViewController: UIViewController {
//IBOutlets
@@ -36,6 +36,7 @@ class ListingPreviewViewController: UIViewController {
private var itemListingDictionary: Dictionary! = Dictionary()
private var alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert)
private var lastListingKey: String!
+ private var newInProgressListing: Dictionary = Dictionary()
override func viewDidLoad() {
super.viewDidLoad()
@@ -100,9 +101,15 @@ class ListingPreviewViewController: UIViewController {
}
}
-
}
+extension Dictionary {
+ mutating func update(other:Dictionary) {
+ for (key,value) in other {
+ self.updateValue(value, forKey:key)
+ }
+ }
+}
//MARK: - FacebookGraphAPIManagerDelegate methods
extension ListingPreviewViewController: FacebookGraphAPIManagerDelegate {
@@ -134,6 +141,7 @@ extension ListingPreviewViewController {
//save listing to private user path in firebase
let newListingRef = self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").childByAutoId()
+ let postingGroup: dispatch_group_t = dispatch_group_create()
//post to ebay
if(self.networksDictionary["ebay"]!){
@@ -150,8 +158,9 @@ extension ListingPreviewViewController {
//post to etsy
if(self.networksDictionary["etsy"]!){
+
+ dispatch_group_enter(postingGroup)
var categoryCode: Int!
- //@FIXME: settings dctionary is staying nil
switch self.itemCategory.text {
case "Accessories":
categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["accessories"] as! Int
@@ -255,17 +264,42 @@ extension ListingPreviewViewController {
"who_made": EtsyRESTAPIManager.settingsDictionary["who_made"] as! String,
"is_supply": EtsyRESTAPIManager.settingsDictionary["is_supply"]!,
"when_made": EtsyRESTAPIManager.settingsDictionary["when_made"] as! String,
+ "shipping_template_id": EtsyRESTAPIManager.settingsDictionary["shipping_template_id"] as! Int,
"state":"draft"
]
- self.etsyManager.sendPOSTRequest("/listings", body: body, onCompletion: {(JSON, NSError) -> Void in print(JSON)})
+ self.etsyManager.sendPOSTRequest("/listings", body: body, onCompletion: {
+ (dict, error) -> Void in
+
+ var results = (dict as! [[String : AnyObject]])[0]
+
+ if((self.newInProgressListing["networkIDs"] == nil)){
+ self.newInProgressListing["networkIDs"] = Dictionary()
+ }
+ var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary)
+ networkIDs["etsy"] = results["listing_id"] as? Int
+ self.newInProgressListing["networkIDs"] = networkIDs
+
+ let imageBody = ["listing_id": networkIDs["etsy"] as! Int,
+ //"type":"image/jpg",
+ "image": UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!]
+
+ self.etsyManager.sendPOSTRequest(("listings/\(networkIDs["etsy"] as! Int)/images"), body: imageBody, onCompletion: {
+ (dict, error) -> Void in
+
+ dispatch_group_leave(postingGroup)
+ })
+
+
+ })
}
//post to facebook
if(self.networksDictionary["facebook"]!){
+ dispatch_group_enter(postingGroup)
let parameters: Dictionary = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!)]
self.lastListingKey = newListingRef.key
@@ -273,54 +307,55 @@ extension ListingPreviewViewController {
//let parameters: Dictionary = ["":""]
-
+ dispatch_group_leave(postingGroup)
}
-
- let listing: Dictionary = ["listingID": newListingRef.key,
- "seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!,
- "listingTitle": self.itemTitle.text,
- "listingPrice": self.itemPrice.text,
- "listingCategory": self.itemCategory.text,
- "listingDescription": self.itemDescription.text,
- "numberOfSupportingImages" : ((self.itemListingDictionary["pictures"] as? [UIImageView])?.count)! - 1,
- "isListingDraft": false,
- "networks": self.networksDictionary]
-
- self.firManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
-
- let databaseDict = snapshot.value as! [String : AnyObject]
-
- let storageRef = self.firManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
-
- //change code to new multi-image saving
+ dispatch_group_notify(postingGroup, dispatch_get_main_queue(), {
+ self.newInProgressListing.update(["listingID": newListingRef.key,
+ "seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!,
+ "listingTitle": self.itemTitle.text,
+ "listingPrice": self.itemPrice.text,
+ "listingCategory": self.itemCategory.text,
+ "listingDescription": self.itemDescription.text,
+ "numberOfSupportingImages" : ((self.itemListingDictionary["pictures"] as? [UIImageView])?.count)! - 1,
+ "isListingDraft": false,
+ "networks": self.networksDictionary])
-
- let listingImageRef = storageRef.child("images/\(newListingRef.key)"+".jpg")
- listingImageRef.putData(UIImageJPEGRepresentation(self.itemPicture.image!, 0.8)!, metadata: nil,completion:
- {(metadata, error) -> Void in
-
- newListingRef.setValue(listing)
-
- self.alert.title = "Listing saved with error"
- self.alert.message = "Your listing has been saved but something went wrong when trying to publish to facebook"
-
-
- //let alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert)
-
- self.alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in self.alert.dismissViewControllerAnimated(true, completion: nil)}))
-
- //register new listing id in global path of firebase root'
- self.firManager.ref.child("Global_listings").child(newListingRef.key).setValue(newListingRef.key)
-
+ self.firManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
+
+ let databaseDict = snapshot.value as! [String : AnyObject]
+
+ let storageRef = self.firManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
+
+ //change code to new multi-image saving
+
+
+
+ let listingImageRef = storageRef.child("images/\(newListingRef.key)"+".jpg")
+ listingImageRef.putData(UIImageJPEGRepresentation(self.itemPicture.image!, 0.8)!, metadata: nil,completion:
+ {(metadata, error) -> Void in
+
+ newListingRef.setValue(self.newInProgressListing)
+
+ // self.alert.title = "Listing saved with error"
+ // self.alert.message = "Your listing has been saved but something went wrong when trying to publish to facebook"
+
+
+ //let alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert)
+
+ // self.alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in self.alert.dismissViewControllerAnimated(true, completion: nil)}))
+
+ //register new listing id in global path of firebase root'
+ self.firManager.ref.child("Global_listings").child(newListingRef.key).setValue(newListingRef.key)
+
+ })
+
+
+
+
+
})
-
-
-
-
-
})
-
}