diff --git a/.DS_Store b/.DS_Store index bf52147..a5ea54c 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Vendoo.xcodeproj/project.pbxproj b/Vendoo.xcodeproj/project.pbxproj index 52b9da5..ffbf866 100644 --- a/Vendoo.xcodeproj/project.pbxproj +++ b/Vendoo.xcodeproj/project.pbxproj @@ -14,6 +14,8 @@ 3E1AA4351D0DD173005FCCBB /* SettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E1AA4341D0DD173005FCCBB /* SettingsViewController.swift */; }; 3E1B1F091D24926C00DBCF08 /* EbaySettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E1B1F081D24926C00DBCF08 /* EbaySettingsViewController.swift */; }; 3E1B1F0B1D2493EE00DBCF08 /* EtsySettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E1B1F0A1D2493EE00DBCF08 /* EtsySettingsViewController.swift */; }; + 3E1DC3CD1D4232490091BC60 /* CategoriesTableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E1DC3CC1D4232490091BC60 /* CategoriesTableViewController.swift */; }; + 3E1DC3CF1D42328C0091BC60 /* CategoryCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E1DC3CE1D42328C0091BC60 /* CategoryCell.swift */; }; 3E4897D11D0067030069F742 /* FirebaseManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E4897D01D0067030069F742 /* FirebaseManager.swift */; }; 3E6CC3571CF2A94B00E00A70 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E6CC3561CF2A94B00E00A70 /* AppDelegate.swift */; }; 3E6CC3591CF2A94B00E00A70 /* SignInViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E6CC3581CF2A94B00E00A70 /* SignInViewController.swift */; }; @@ -71,6 +73,8 @@ 3E1AA4341D0DD173005FCCBB /* SettingsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SettingsViewController.swift; sourceTree = ""; }; 3E1B1F081D24926C00DBCF08 /* EbaySettingsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EbaySettingsViewController.swift; sourceTree = ""; }; 3E1B1F0A1D2493EE00DBCF08 /* EtsySettingsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EtsySettingsViewController.swift; sourceTree = ""; }; + 3E1DC3CC1D4232490091BC60 /* CategoriesTableViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CategoriesTableViewController.swift; sourceTree = ""; }; + 3E1DC3CE1D42328C0091BC60 /* CategoryCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CategoryCell.swift; sourceTree = ""; }; 3E4897D01D0067030069F742 /* FirebaseManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FirebaseManager.swift; sourceTree = ""; }; 3E6CC3531CF2A94B00E00A70 /* Vendoo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Vendoo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 3E6CC3561CF2A94B00E00A70 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -316,6 +320,8 @@ 3EC3252B1CF8944800626C48 /* NewItemPostingSession */ = { isa = PBXGroup; children = ( + 3E1DC3CE1D42328C0091BC60 /* CategoryCell.swift */, + 3E1DC3CC1D4232490091BC60 /* CategoriesTableViewController.swift */, 3EC3252C1CF894C400626C48 /* ItemImagePickerViewController.swift */, 3ECEDB861CF9C722003566B3 /* ListingPreviewViewController.swift */, ); @@ -634,12 +640,14 @@ 3EC325201CF7C3AB00626C48 /* NetworkTableViewCell.swift in Sources */, 3EC325261CF7E90000626C48 /* FacebookGraphAPIManager.swift in Sources */, 3E7CF3FC1CF5FE9400F486B2 /* RecoverPasswordViewController.swift in Sources */, + 3E1DC3CF1D42328C0091BC60 /* CategoryCell.swift in Sources */, 3EC325111CF703A600626C48 /* ItemCell.swift in Sources */, 3EA668A11D02836C00EE57A8 /* EbayWebServiceManager.swift in Sources */, 3ECEDB871CF9C722003566B3 /* ListingPreviewViewController.swift in Sources */, 3E1B1F0B1D2493EE00DBCF08 /* EtsySettingsViewController.swift in Sources */, 3EC325231CF7DA5500626C48 /* HomeViewController.swift in Sources */, 3EC3252D1CF894C400626C48 /* ItemImagePickerViewController.swift in Sources */, + 3E1DC3CD1D4232490091BC60 /* CategoriesTableViewController.swift in Sources */, 3E7CF4011CF6366300F486B2 /* EtsyRESTAPIManager.swift in Sources */, 3EC325151CF7104300626C48 /* ItemTableViewController.swift in Sources */, 3EFB0E331D0B968300A05D7A /* SideMenuView.swift in Sources */, diff --git a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/UserInterfaceState.xcuserstate index fdaef2a..8a12093 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 caa82d4..dfbaa09 100644 --- a/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ b/Vendoo.xcworkspace/xcuserdata/okechi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -9,13 +9,45 @@ shouldBeEnabled = "No" ignoreCount = "0" continueAfterRunningActions = "No" - filePath = "Vendoo/EbayWebServiceManager.swift" - timestampString = "490072640.74786" + filePath = "Vendoo/EtsyRESTAPIManager.swift" + timestampString = "491361523.935232" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" - startingLineNumber = "282" - endingLineNumber = "282" - landmarkName = "parser(_:foundCharacters:)" + startingLineNumber = "231" + endingLineNumber = "231" + landmarkName = "authorizeApp(_:)" + landmarkType = "5"> + + + + + + + + @@ -25,110 +57,576 @@ shouldBeEnabled = "No" ignoreCount = "0" continueAfterRunningActions = "No" - filePath = "Vendoo/EbayWebServiceManager.swift" - timestampString = "490072640.74786" + filePath = "Vendoo/EtsyRESTAPIManager.swift" + timestampString = "491361523.935232" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" - startingLineNumber = "62" - endingLineNumber = "62" - landmarkName = "init()" + startingLineNumber = "523" + endingLineNumber = "523" + landmarkName = "sendPOSTRequest(_:body:onCompletion:)" landmarkType = "5"> + startingLineNumber = "403" + endingLineNumber = "403" + landmarkName = "sendGETRequest(_:onCompletion:)" + landmarkType = "5"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + startingLineNumber = "216" + endingLineNumber = "216" + offsetFromSymbolStart = "4169"> + startingLineNumber = "219" + endingLineNumber = "219" + offsetFromSymbolStart = "43"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + startingLineNumber = "639" + endingLineNumber = "639" + offsetFromSymbolStart = "51"> + + + + + + + + + startingLineNumber = "639" + endingLineNumber = "639" + offsetFromSymbolStart = "51"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - @@ -231,13 +649,221 @@ shouldBeEnabled = "Yes" ignoreCount = "0" continueAfterRunningActions = "No" - filePath = "Vendoo/HomeViewController.swift" - timestampString = "490366185.766714" + filePath = "Vendoo/EtsyRESTAPIManager.swift" + timestampString = "491460836.27789" startingColumnNumber = "9223372036854775807" endingColumnNumber = "9223372036854775807" - startingLineNumber = "73" - endingLineNumber = "73" - landmarkName = "viewDidLoad()" + startingLineNumber = "583" + endingLineNumber = "583" + landmarkName = "sendPOSTRequest(_:body:onCompletion:)" + landmarkType = "5"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Vendoo/.DS_Store b/Vendoo/.DS_Store index c12975b..1b9a41c 100644 Binary files a/Vendoo/.DS_Store and b/Vendoo/.DS_Store differ diff --git a/Vendoo/CategoriesTableViewController.swift b/Vendoo/CategoriesTableViewController.swift new file mode 100644 index 0000000..f654cea --- /dev/null +++ b/Vendoo/CategoriesTableViewController.swift @@ -0,0 +1,195 @@ +// +// CategoriesTableViewController.swift +// Vendoo +// +// Created by Okechi Onyeje on 7/16/16. +// Copyright © 2016 Okechi Onyeje. All rights reserved. +// + +import UIKit + +class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { + + private var itemListingDictionary: Dictionary! = Dictionary() + private var graphManager: FacebookGraphAPIManager! = nil + private var firManager: FirebaseManager! = nil + private var etsyManager: EtsyRESTAPIManager! = nil + private var ebayManager: EbayWebServiceManager! = EbayWebServiceManager() + private var selectedCategory: String! + + private var categories = ["Accessories", + "Art", + "Bath & Beauty", + "Bags & Purses", + "Books", + "Candles", + "Ceramics & Pottery", + "Children", + "Clothing", + "Crochet", + "Dolls & Miniatures", + "Everything Else", + "Furniture", + "Geekery", + "Glass", + "Holidays", + "Houseware", + "Jewelry", + "Knitting", + "Music", + "Needlecraft", + "Paper Goods", + "Patterns", + "Plants and Edibles", + "Quilts", + "Supplies", + "Toys", + "Vintage", + "Wedding", + "Woodworking"] + @IBOutlet weak var table: UITableView! + + + override func viewDidLoad() { + super.viewDidLoad() + + self.table.delegate = self + self.table.dataSource = self + // Uncomment the following line to preserve selection between presentations + // self.clearsSelectionOnViewWillAppear = false + + // Uncomment the following line to display an Edit button in the navigation bar for this view controller. + // self.navigationItem.rightBarButtonItem = self.editButtonItem() + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + // MARK: - Table view data source + + func numberOfSectionsInTableView(tableView: UITableView) -> Int { + // #warning Incomplete implementation, return the number of sections + return 1 + } + + func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + // #warning Incomplete implementation, return the number of rows + return self.categories.count + } + + + func setListingDictionary(listingDictionary: Dictionary){ + + self.itemListingDictionary = listingDictionary + + } + + func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager, etsyManager: EtsyRESTAPIManager){ + self.graphManager = fbManager + self.firManager = fireManager + self.ebayManager = ebayManager + self.etsyManager = etsyManager + } + + func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + let cell: CategoryCell! = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as? CategoryCell + + // Configure the cell... + + dispatch_async(dispatch_get_main_queue(), { + cell.categoryName.text = self.categories[indexPath.row] + + //ebay + if(true){ + cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true + } + //amazon + if(true){ + cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true + } + //etsy + if(false){ + cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true + + } + //facebook + if(false){ + cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = true + } + + }) + + + return cell + } + + + func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + self.selectedCategory = self.categories[indexPath.row] + self.performSegueWithIdentifier("NetworkSelectionSegue", sender: self) + } + + /* + // Override to support conditional editing of the table view. + override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { + // Return false if you do not want the specified item to be editable. + return true + } + */ + + /* + // Override to support editing the table view. + override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { + if editingStyle == .Delete { + // Delete the row from the data source + tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) + } else if editingStyle == .Insert { + // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view + } + } + */ + + /* + // Override to support rearranging the table view. + override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { + + } + */ + + /* + // Override to support conditional rearranging of the table view. + override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { + // Return false if you do not want the item to be re-orderable. + return true + } + */ + + + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { + // Get the new view controller using segue.destinationViewController. + // Pass the selected object to the new view controller. + + if(segue.identifier == "NetworkSelectionSegue") { + self.itemListingDictionary["category"] = self.selectedCategory + (segue.destinationViewController as! NetworksTableViewController).setListingDictionary(self.itemListingDictionary) + (segue.destinationViewController as! NetworksTableViewController).setManagers(self.graphManager, + fireManager: self.firManager, ebayManager: self.ebayManager, etsyManager: self.etsyManager ) + + (segue.destinationViewController as! NetworksTableViewController).setNetworkSelectFunctionality(true) + //print(self.categoryPicker.selectedRowInComponent(0)) + } + } + + + @IBAction func cancelCategorySelection(sender: AnyObject) { + + self.dismissViewControllerAnimated(true, completion: nil) + } + + +} diff --git a/Vendoo/CategoryCell.swift b/Vendoo/CategoryCell.swift new file mode 100644 index 0000000..c71f8aa --- /dev/null +++ b/Vendoo/CategoryCell.swift @@ -0,0 +1,113 @@ +// +// CategoryCell.swift +// Vendoo +// +// Created by Okechi Onyeje on 7/18/16. +// Copyright © 2016 Okechi Onyeje. All rights reserved. +// + +import UIKit + +class CategoryCell: UITableViewCell, UICollectionViewDelegate { + + @IBOutlet weak var categoryName: UILabel! + @IBOutlet weak var networks: UICollectionView! + + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.networks.delegate = self + self.networks.dataSource = self + self.networks.backgroundView?.backgroundColor = UIColor.whiteColor() + } + + override func setSelected(selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + +} + + + +// MARK: UICollectionViewDataSource +extension CategoryCell: UICollectionViewDataSource{ + + func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { + // #warning Incomplete implementation, return the number of sections + return 1 + } + + + func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + // #warning Incomplete implementation, return the number of items + return 4 + } + + func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { + + let cell: UICollectionViewCell! + + switch (indexPath.row){ + case 0: + cell = collectionView.dequeueReusableCellWithReuseIdentifier("ebay", forIndexPath: indexPath) + break + case 1: + cell = collectionView.dequeueReusableCellWithReuseIdentifier("amazon", forIndexPath: indexPath) + break + case 2: + cell = collectionView.dequeueReusableCellWithReuseIdentifier("etsy", forIndexPath: indexPath) + break + default: + cell = collectionView.dequeueReusableCellWithReuseIdentifier("facebook", forIndexPath: indexPath) + break + } + + + // Configure the cell (in this case show or hide the cell depending on which network the item is being listed on) + + return cell + } + + +} + + +// MARK: UICollectionViewDelegate +extension CategoryCell { + + /* + // Uncomment this method to specify if the specified item should be highlighted during tracking + override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { + return true + } + */ + + /* + // Uncomment this method to specify if the specified item should be selected + override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { + return true + } + */ + + /* + // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item + override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { + return false + } + + override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { + return false + } + + override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { + + } + */ + +} + + + diff --git a/Vendoo/EtsyRESTAPIManager.swift b/Vendoo/EtsyRESTAPIManager.swift index 3531e87..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 { @@ -73,7 +73,7 @@ class EtsyRESTAPIManager: NSObject { EtsyRESTAPIManager.settingsDictionary = ([ "who_made":"i_did", - "is_supply":"true", + "is_supply":true, "when_made":"made_to_order" ] as Dictionary) @@ -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..90c538d 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,32 +153,33 @@ 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 '/' - func makePOSTResquest(requestPath: String!, params: [NSObject: AnyObject]!){ + func makePOSTResquest(requestPath: String!, var params: [NSObject: AnyObject]!, onComplete: ServiceResponse){ - /*if(FBSDKAccessToken.currentAccessToken() != nil && FBSDKAccessToken.currentAccessToken().hasGranted("pubish_actions")){*/ + if(FBSDKAccessToken.currentAccessToken() != nil && FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions")){ + params["access_token"] = self.apiKey + "|" + self.apiSecret - let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: requestPath, parameters: params, HTTPMethod: "POST") + let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: requestPath + "?access_token=" + FBSDKAccessToken.currentAccessToken().tokenString, parameters: params, HTTPMethod: "POST") graphRequest.startWithCompletionHandler({ (id, result, error) -> Void in @@ -186,21 +187,22 @@ extension FacebookGraphAPIManager { if(error == nil){ print(result["id"]) - self.delegate?.listingUploadedFB((result["id"] as? String)!) + //self.delegate?.listingUploadedFB((result["id"] as? String)!) print(result) + onComplete((result["id"] as? String)!, nil) } else{ - + print(error) } //save id in firebase so retrieval can be done later }) - //} + } /*else{ - print("must reauthenticate facebook") - }*/ - - } + print("must reauthenticate facebook") + } + + */} //used to delete permissions and listings from users timeline, path must start with '/' func makeDELETIONResquest(requestPath: String!, params: [NSObject: AnyObject]!) -> Bool{ @@ -232,5 +234,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/ItemImagePickerViewController.swift b/Vendoo/ItemImagePickerViewController.swift index e110fc3..64d2ec7 100644 --- a/Vendoo/ItemImagePickerViewController.swift +++ b/Vendoo/ItemImagePickerViewController.swift @@ -23,7 +23,7 @@ class ItemImagePickerViewController: UIViewController { @IBOutlet weak var possibleItemImage3: UIImageView! @IBOutlet weak var possibleItemImage4: UIImageView! @IBOutlet weak var possibleItemImage5: UIImageView! - + @IBOutlet weak var itemQuantity: UITextField! @IBOutlet weak var itemName: UITextField! @IBOutlet weak var itemDescription: UITextView! @IBOutlet weak var itemPrice: UITextField! @@ -48,6 +48,7 @@ class ItemImagePickerViewController: UIViewController { self.categoryPicker.dataSource = self self.itemDescription.delegate = self self.itemName.delegate = self + self.itemQuantity.delegate = self self.itemPrice.delegate = self self.picker.delegate = self @@ -91,13 +92,13 @@ extension ItemImagePickerViewController { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. - if(segue.identifier == "SelectNetworkSegue"){ + if(segue.identifier == "CategoriesSegue"){ print(self.itemName.text!) print(self.itemDescription.text!) print(self.possibleItemImageMain.image) print(self.itemPrice.text!) - var dict: Dictionary = ["title":self.itemName.text!, "description":self.itemDescription.text!, "price":self.itemPrice.text!, "category":self.pickerData[self.categoryPicker.selectedRowInComponent(0)]] + var dict: Dictionary = ["title":self.itemName.text!, "description":self.itemDescription.text!, "price":self.itemPrice.text!, "quantity":self.itemQuantity.text!] var counter = 0 var images: [UIImageView] = [] for bool in self.itemImagesSelections { @@ -124,12 +125,13 @@ extension ItemImagePickerViewController { } dict["pictures"] = images - (segue.destinationViewController as! NetworksTableViewController).setListingDictionary(dict) - (segue.destinationViewController as! NetworksTableViewController).setManagers(((self.tabBarController as? HomeViewController)?.fbGraphManager)!, - fireManager: ((self.tabBarController as? HomeViewController)?.firebaseManager)!, ebayManager: ((self.tabBarController as? HomeViewController)?.ebayGraphManager)! ) + (segue.destinationViewController as! CategoriesTableViewController).setListingDictionary(dict) + (segue.destinationViewController as! CategoriesTableViewController).setManagers(((self.tabBarController as? HomeViewController)?.fbGraphManager)!, + fireManager: ((self.tabBarController as? HomeViewController)?.firebaseManager)!, ebayManager: ((self.tabBarController as? HomeViewController)?.ebayGraphManager)!, + etsyManager: ((self.tabBarController as? HomeViewController)?.etsyManager)!) - (segue.destinationViewController as! NetworksTableViewController).setNetworkSelectFunctionality(true) - print(self.categoryPicker.selectedRowInComponent(0)) + //(segue.destinationViewController as! NetworksTableViewController).setNetworkSelectFunctionality(true) + //print(self.categoryPicker.selectedRowInComponent(0)) } diff --git a/Vendoo/ListingPreviewViewController.swift b/Vendoo/ListingPreviewViewController.swift index 1504dc6..bb908a1 100644 --- a/Vendoo/ListingPreviewViewController.swift +++ b/Vendoo/ListingPreviewViewController.swift @@ -14,11 +14,12 @@ */ 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 @IBOutlet weak var containerScrollView: UIScrollView! + @IBOutlet weak var itemQuantity: UITextView! @IBOutlet weak var itemPicture: UIImageView! @IBOutlet weak var itemTitle: UITextView! @IBOutlet weak var itemDescription: UITextView! @@ -31,26 +32,28 @@ class ListingPreviewViewController: UIViewController { private var graphManager: FacebookGraphAPIManager! = nil private var firManager: FirebaseManager! = nil private var ebayManager: EbayWebServiceManager! = nil + private var etsyManager: EtsyRESTAPIManager! = nil 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() - + // Do any additional setup after loading the view. // Initialization code self.networks.delegate = self self.networks.dataSource = self self.networks.backgroundView?.backgroundColor = UIColor.whiteColor() - self.graphManager.delegate = self + //self.graphManager.delegate = self } override func viewDidAppear(animated: Bool) { self.setListing() } - + override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. @@ -64,6 +67,7 @@ class ListingPreviewViewController: UIViewController { self.itemDescription.text = self.itemListingDictionary["description"] as! String self.itemPrice.text = self.itemListingDictionary["price"] as! String self.itemCategory.text = self.itemListingDictionary["category"] as! String + self.itemQuantity.text = self.itemListingDictionary["quantity"] as! String } func setDictionary(netdictionary:Dictionary, itemdictionary: Dictionary){ @@ -71,16 +75,17 @@ class ListingPreviewViewController: UIViewController { self.itemListingDictionary = itemdictionary } - func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager){ + func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager, etsyManager: EtsyRESTAPIManager){ self.graphManager = fbManager self.firManager = fireManager self.ebayManager = ebayManager + self.etsyManager = etsyManager } - + // MARK: - Navigation - + // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. @@ -92,30 +97,37 @@ class ListingPreviewViewController: UIViewController { vc.itemPrice.text? = self.itemPrice.text vc.itemDescription.text? = self.itemDescription.text vc.possibleItemImageMain = self.itemPicture + vc.itemQuantity.text? = self.itemQuantity.text } } - - + } - -//MARK: - FacebookGraphAPIManagerDelegate methods -extension ListingPreviewViewController: FacebookGraphAPIManagerDelegate { - func listingUploadedFB(fbID: String) { - - self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").child(self.lastListingKey).updateChildValues(["network_listing_IDs":["fbID":fbID]]) - - self.alert.title = "Listing Published" - self.alert.message = "Your listing has been published to facebook" - - self.presentViewController(self.alert, animated: true, completion: nil) +extension Dictionary { + mutating func update(other:Dictionary) { + for (key,value) in other { + self.updateValue(value, forKey:key) + } } } - +/* + //MARK: - FacebookGraphAPIManagerDelegate methods + extension ListingPreviewViewController: FacebookGraphAPIManagerDelegate { + func listingUploadedFB(fbID: String) { + + self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").child(self.lastListingKey).updateChildValues(["network_listing_IDs":["fbID":fbID]]) + + self.alert.title = "Listing Published" + self.alert.message = "Your listing has been published to facebook" + + self.presentViewController(self.alert, animated: true, completion: nil) + } + } + */ //MARK: - IBActions extension ListingPreviewViewController { - + @IBAction func publishItem(sender: AnyObject) { @@ -125,7 +137,12 @@ extension ListingPreviewViewController { self.presentViewController(alert, animated: true, completion: nil) }else{ - + self.networksDictionary["areNetworksChosen"] = true + + //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"]!){ @@ -138,82 +155,241 @@ extension ListingPreviewViewController { } + //post to etsy if(self.networksDictionary["etsy"]!){ + dispatch_group_enter(postingGroup) + var categoryCode: Int! + switch self.itemCategory.text { + case "Accessories": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["accessories"] as! Int + break + case "Art": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["art"] as! Int + break + case "Bath & Beauty": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["bath_and_beauty"] as! Int + break + case "Bags & Purses": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["bags_and_purses"] as! Int + break + case "Books": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["books_and_zines"] as! Int + break + case "Candles": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["candles"] as! Int + break + case "Ceramics & Pottery": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["ceramics_and_pottery"] as! Int + break + case "Children": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["children"] as! Int + break + case "Clothing": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["clothing"] as! Int + break + case "Crochet": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["crochet"] as! Int + break + case "Dolls & Miniatures": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["dolls_and_miniatures"] as! Int + break + case "Everything Else": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["everything_else"] as! Int + break + case "Furniture": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["furniture"] as! Int + break + case "Geekery": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["geekery"] as! Int + break + case "Glass": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["glass"] as! Int + break + case "Holidays": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["holidays"] as! Int + break + case "Houseware": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["housewares"] as! Int + break + case "Jewelry": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["jewelry"] as! Int + break + case "Knitting": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["knitting"] as! Int + break + case "Music": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["music"] as! Int + break + case "Needlecraft": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["needlecraft"] as! Int + break + case "Paper Goods": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["paper_goods"] as! Int + break + case "Patterns": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["patterns"] as! Int + break + case "Plants and Edibles": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["plants_and_edibles"] as! Int + break + case "Quilts": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["quilts"] as! Int + break + case "Supplies": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["supplies"] as! Int + break + case "Toys": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["toys"] as! Int + break + case "Vintage": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["vintage"] as! Int + break + case "Wedding": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["weddings"] as! Int + break + case "Woodworking": + categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["woodworking"] as! Int + break + default: + break + } + + let body: [String: AnyObject] = [ "title": self.itemTitle.text, + "quantity":self.itemQuantity.text, + "description":self.itemDescription.text, + "price":self.itemPrice.text, + "category_id":categoryCode, + "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: { + (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) + }) + + + }) + } - - //save listing to private user path in firebase - let newListingRef = self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").childByAutoId() - self.networksDictionary["areNetworksChosen"] = true - 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 + //post to facebook + if(self.networksDictionary["facebook"]!){ + dispatch_group_enter(postingGroup) - let databaseDict = snapshot.value as! [String : AnyObject] + let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true) + let fileURL = tmpDirURL.URLByAppendingPathComponent("main").URLByAppendingPathExtension("jpg") + print("FilePath: \(fileURL.path!)") + do { + try UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!.writeToFile(fileURL.path!, options: NSDataWritingOptions.AtomicWrite) + }catch{ + (error) + print(error) + } - let storageRef = self.firManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!) + //let parameters: Dictionary = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!)] - //change code to new multi-image saving + let parameters: Dictionary = ["Source": UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!, "published":false] - - - let listingImageRef = storageRef.child("images/\(newListingRef.key)"+".jpg") - listingImageRef.putData(UIImageJPEGRepresentation(self.itemPicture.image!, 0.8)!, metadata: nil,completion: - {(metadata, error) -> Void in + self.lastListingKey = newListingRef.key + self.graphManager.makePOSTResquest("me/photos", params: parameters, onComplete: { + (imageId, error) -> Void in + + var listingParams: Dictionary = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!), "attached_media[0]":"{\"media_fbid\":\"\(imageId as! String)\"}"] + self.graphManager.makePOSTResquest("me/feed", params: listingParams, onComplete: { + (listingId, 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)})) - - let parameters: Dictionary = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!)] - - - - - //post to facebook - if(self.networksDictionary["facebook"]!){ - - //need to reverse process and upload to firebase last so that all network listing id's can be saved to firebase for notification access. - self.lastListingKey = newListingRef.key - self.graphManager.makePOSTResquest("me/feed", params: parameters) - - //let parameters: Dictionary = ["":""] - - + if((self.newInProgressListing["networkIDs"] == nil)){ + self.newInProgressListing["networkIDs"] = Dictionary() } - - - - - - //register new listing id in global path of firebase root' - self.firManager.ref.child("Global_listings").child(newListingRef.key).setValue(newListingRef.key) + var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary) + networkIDs["facebook"] = listingId as! String + self.newInProgressListing["networkIDs"] = networkIDs + dispatch_group_leave(postingGroup) + + }) + /* + + */ }) + //let parameters: Dictionary = ["":""] + } + + 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]) + 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) + + }) + + + + + + }) }) - } diff --git a/Vendoo/Main.storyboard b/Vendoo/Main.storyboard index b9fabd0..2a49c19 100755 --- a/Vendoo/Main.storyboard +++ b/Vendoo/Main.storyboard @@ -377,7 +377,7 @@ - + @@ -418,6 +418,9 @@ + + + @@ -437,6 +440,7 @@ + @@ -1025,6 +1029,7 @@ + @@ -1995,7 +2000,7 @@ - + @@ -2005,549 +2010,100 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2560,6 +2116,9 @@ + + + @@ -2568,10 +2127,14 @@ + + + + - + @@ -2813,8 +2376,9 @@ - - + + + diff --git a/Vendoo/NetworksTableViewController.swift b/Vendoo/NetworksTableViewController.swift index a90dddf..0ec9a96 100644 --- a/Vendoo/NetworksTableViewController.swift +++ b/Vendoo/NetworksTableViewController.swift @@ -88,10 +88,11 @@ extension NetworksTableViewController { } - func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager){ + func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager, etsyManager: EtsyRESTAPIManager){ self.graphManager = fbManager self.firManager = fireManager self.ebayManager = ebayManager + self.etsyManager = etsyManager } } @@ -108,7 +109,7 @@ extension NetworksTableViewController { if(segue.identifier == "ItemPreviewSegue"){ (segue.destinationViewController as! ListingPreviewViewController).setDictionary(self.networksDictionary, itemdictionary: self.itemListingDictionary) - (segue.destinationViewController as! ListingPreviewViewController).setManagers(self.graphManager, fireManager: self.firManager, ebayManager: self.ebayManager) + (segue.destinationViewController as! ListingPreviewViewController).setManagers(self.graphManager, fireManager: self.firManager, ebayManager: self.ebayManager, etsyManager: self.etsyManager) } if(segue.identifier == "EtsySettingsSegue") { @@ -415,12 +416,12 @@ extension NetworksTableViewController: UITableViewDelegate { cell = (self.tableView.dequeueReusableCellWithIdentifier("etsy", forIndexPath: indexPath) as! EtsyTableViewCell) cell.setSelected(false, animated: false) - //selection code for etsy if(cell.networkToggle.on == true){ dispatch_async(dispatch_get_main_queue(), { () -> Void in cell.networkToggle.setOn(false, animated: true) + cell.networkToggle.on = false }) //code to deselect network @@ -430,6 +431,7 @@ extension NetworksTableViewController: UITableViewDelegate { dispatch_async(dispatch_get_main_queue(), { () -> Void in cell.networkToggle.setOn(true, animated: true) + cell.networkToggle.on = true }) //code to select network self.networksDictionary["etsy"] = true @@ -441,7 +443,7 @@ extension NetworksTableViewController: UITableViewDelegate { (tabBar as? HomeViewController)?.etsyManager.authorizeApp(self) */ - + } break @@ -489,7 +491,7 @@ extension NetworksTableViewController: UITableViewDelegate { } else{ - + /* //case where class is being used to authorize a network for the app to post on switch (indexPath.row){ case 0: @@ -630,7 +632,7 @@ extension NetworksTableViewController: UITableViewDelegate { break } - +*/ } @@ -753,6 +755,14 @@ extension NetworksTableViewController { }) break case is FBTableViewCell.Type: + let tabBar = self.tabBarController + ((tabBar as? HomeViewController)?.fbGraphManager.authorizeApp(self))! + dispatch_async(dispatch_get_main_queue(), { + sender.setTitle("Logout", forState: UIControlState.Normal) + (sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = true + (sender.superview?.superview as! FBTableViewCell).settingsBtn.hidden = false + }) + break default: break @@ -783,6 +793,13 @@ extension NetworksTableViewController { }) break case is FBTableViewCell.Type: + let tabBar = self.tabBarController + ((tabBar as? HomeViewController)?.fbGraphManager.deAuthorizeApp(self))! + dispatch_async(dispatch_get_main_queue(), { + sender.setTitle("Login", forState: UIControlState.Normal) + (sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = false + (sender.superview?.superview as! FBTableViewCell).settingsBtn.hidden = true + }) break default: break