Merged branch Comment-Source-Code into master

This commit is contained in:
Okechi Onyeje 2016-11-29 19:02:18 -05:00
commit 04d4aeddb8
21 changed files with 317 additions and 2436 deletions

View File

@ -28,6 +28,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
let storyboard = UIStoryboard(name: "Main", bundle: nil) let storyboard = UIStoryboard(name: "Main", bundle: nil)
let view: UIViewController! let view: UIViewController!
//based on if there is a currently logged in user, the entry view controller will either be signin or sign up
if NSUserDefaults.standardUserDefaults().boolForKey("signedIn"){ if NSUserDefaults.standardUserDefaults().boolForKey("signedIn"){
view = storyboard.instantiateViewControllerWithIdentifier("SignInViewController") view = storyboard.instantiateViewControllerWithIdentifier("SignInViewController")
}else { }else {
@ -73,6 +75,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
extension AppDelegate { extension AppDelegate {
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
//set up oauth for use with etsy
if (url.host == "oauth-callback") { if (url.host == "oauth-callback") {
print(url) print(url)
let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)

View File

@ -136,415 +136,6 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
//leaving this in for category debugging purposes
/*
switch (cell.categoryName.text!) {
case ("Accessories") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Antiques") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Art") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Baby") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Bags & Purses") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Bath, Beauty & Health") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Books") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Business & Industrial") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Cameras & Photo") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Candles") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Cell Phones & Accessories") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Clothing & Shoes") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Ceramics & Pottery") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Children") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Coins & Paper Money") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Collectibles") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Computers/Tablets & Networking") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Consumer Electronics") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Crafts") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Dolls & Miniatures") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("DVDs & Movies") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Entertainment Memorabilia") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Everything Else") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Furniture") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Gift Cards & Coupons") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Geekery") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Glass") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Holidays") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Home/Houseware & Garden") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Jewelry & Watches") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Knitting") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Music") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Musical Instruments & Gear") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Needlecraft") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Paper Goods") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Patterns") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Pet Supplies") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Pottery & Glass") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Plants and Edibles") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Quilts") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Real Estate") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Specialty Services") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Sporting Goods") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Sports Memorabilia & Fan Shop") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Stamps") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Supplies") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Tickets & Experiences") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Toys & Hobbies") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Travel") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Video Games & Consoles") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = false //ebay
//ask to drill into ebay categories
cell.shouldAskAboutLeafCategories = true
break
case ("Vintage") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Wedding") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
case ("Woodworking") :
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = false //facebook
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = false //etsy
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true //amazon
cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true //ebay
break
default:
break
}*/
/*//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
}*/
}) })
@ -567,6 +158,8 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
popover!.sourceRect = CGRectMake(100,100,50,50) popover!.sourceRect = CGRectMake(100,100,50,50)
popoverContent.setManagers(self.ebayManager) popoverContent.setManagers(self.ebayManager)
//dynamically loads ebay categories until leaf category is reached
popoverContent.loadCategories(self.selectedCategory, selectedCatCompletion: { popoverContent.loadCategories(self.selectedCategory, selectedCatCompletion: {
(categoryID, error) -> Void in (categoryID, error) -> Void in
self.selectedSub = categoryID as! String self.selectedSub = categoryID as! String
@ -696,11 +289,13 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
let cell: CategoryCell! = tableView.cellForRowAtIndexPath(indexPath) as! CategoryCell//tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as? CategoryCell let cell: CategoryCell! = tableView.cellForRowAtIndexPath(indexPath) as! CategoryCell//tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as? CategoryCell
if(self.ebayManager.isAuthorized ) { if(self.ebayManager.isAuthorized ) {
//checks if the selected category is a leaf, if it is then go to choose networks else dynamically load child categories
var dict: Dictionary<String, Dictionary<String, AnyObject>> = (EbayWebServiceManager.settingsDictionary["categories"]!) as! Dictionary<String, Dictionary<String, AnyObject>> var dict: Dictionary<String, Dictionary<String, AnyObject>> = (EbayWebServiceManager.settingsDictionary["categories"]!) as! Dictionary<String, Dictionary<String, AnyObject>>
let catDict = dict[self.selectedCategory] let catDict = dict[self.selectedCategory]
if (catDict != nil && !(catDict!["isLeaf"] as! Bool)){ if (catDict != nil && !(catDict!["isLeaf"] as! Bool)){
self.potentialEbay = true self.potentialEbay = true //determines whether ebay should be an option for posting
self.navigateCategories() self.navigateCategories()
} }
else{ else{
@ -712,41 +307,6 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
} }
} }
/*
// 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 // MARK: - Navigation
@ -777,7 +337,6 @@ class CategoriesTableViewController: UIViewController, UITableViewDelegate, UITa
if self.potentialAmazon { if self.potentialAmazon {
(segue.destinationViewController as! NetworksTableViewController).toggleMarketPlaceVisibitlity("amazon") (segue.destinationViewController as! NetworksTableViewController).toggleMarketPlaceVisibitlity("amazon")
} }
//print(self.categoryPicker.selectedRowInComponent(0))
} }
} }

View File

@ -36,7 +36,6 @@ class CategoryPopUpController: UIViewController {
self.ebayManager = ebayManager self.ebayManager = ebayManager
} }
//@FIXME: Fix category selection for retrieving categories id values, hybrid categories don't work with this and have to manually add these
func loadCategories( selectedCategory: String, selectedCatCompletion: ServiceResponse?) { func loadCategories( selectedCategory: String, selectedCatCompletion: ServiceResponse?) {
self.parentCategory.append(selectedCategory) self.parentCategory.append(selectedCategory)
var catCode: String! var catCode: String!

View File

@ -89,6 +89,7 @@ extension EbaySettingsViewController {
} }
//@TODO options for switching default settings for ebay listing will be added during beta testing after user input phase
@IBAction func selectListingType(sender: AnyObject) { @IBAction func selectListingType(sender: AnyObject) {
} }

View File

@ -21,9 +21,13 @@ class EbayWebServiceManager: NSObject {
//----------------------------------------------// //----------------------------------------------//
let baseURL = "https://api.sandbox.ebay.com/ws/api.dll" let baseURL = "https://api.sandbox.ebay.com/ws/api.dll"
//api credentials for app
private var apiKey: String! private var apiKey: String!
private var devKey: String! private var devKey: String!
private var certID: String! private var certID: String!
var isAuthorized: Bool = NSUserDefaults.standardUserDefaults().boolForKey("ebayAuthorized")
//request variables
private var mutableData: NSMutableData = NSMutableData() private var mutableData: NSMutableData = NSMutableData()
private var currentElementName:NSString = "" private var currentElementName:NSString = ""
private var catID: NSString! private var catID: NSString!
@ -33,8 +37,9 @@ class EbayWebServiceManager: NSObject {
private var userEmail:String = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)! private var userEmail:String = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!
private var signinURL: String! private var signinURL: String!
private var xmlResponseDictionary: Dictionary<String, AnyObject!> = Dictionary<String, AnyObject!>() private var xmlResponseDictionary: Dictionary<String, AnyObject!> = Dictionary<String, AnyObject!>()
//class variables
var delegate: EbayWebServiceManagerDelegate? var delegate: EbayWebServiceManagerDelegate?
var isAuthorized: Bool = NSUserDefaults.standardUserDefaults().boolForKey("ebayAuthorized")
static var settingsDictionary = Dictionary<String , AnyObject>() static var settingsDictionary = Dictionary<String , AnyObject>()
private var subCategories = Dictionary<String, Dictionary<String, AnyObject>>() private var subCategories = Dictionary<String, Dictionary<String, AnyObject>>()
private var completion: ServiceResponse! private var completion: ServiceResponse!
@ -107,6 +112,7 @@ class EbayWebServiceManager: NSObject {
//MARK: - authentication methods //MARK: - authentication methods
extension EbayWebServiceManager { extension EbayWebServiceManager {
//used to set up all xml requests when making calls to ebay service
private func requestMaker(soapMessage: String!, theRequest: NSMutableURLRequest!) { private func requestMaker(soapMessage: String!, theRequest: NSMutableURLRequest!) {
let msgLength = soapMessage.characters.count let msgLength = soapMessage.characters.count
theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type") theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type")
@ -118,6 +124,8 @@ extension EbayWebServiceManager {
theRequest.addValue("0", forHTTPHeaderField: "X-EBAY-API-SITEID") theRequest.addValue("0", forHTTPHeaderField: "X-EBAY-API-SITEID")
theRequest.addValue("", forHTTPHeaderField: "SOAPAction") theRequest.addValue("", forHTTPHeaderField: "SOAPAction")
theRequest.HTTPMethod = "POST" theRequest.HTTPMethod = "POST"
//adds xml soap message to request before starting call
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true) let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
connection!.start() connection!.start()
@ -127,6 +135,7 @@ extension EbayWebServiceManager {
} }
} }
//authorize ebay for use with app by first getting a sessionID
func authorizeApp(onComplete: ServiceResponse){ func authorizeApp(onComplete: ServiceResponse){
let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
@ -143,8 +152,8 @@ extension EbayWebServiceManager {
} }
func deauthorizeApp(){ func deauthorizeApp(){
//@TODO: Add an alert to let user know if their account has not been deauthorized and keep them logged in.
var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<RevokeTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" + "<RevokeTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
"<RequesterCredentials>" + "<RequesterCredentials>" +
@ -176,6 +185,7 @@ extension EbayWebServiceManager {
} }
} }
//used to retrieve users paypal email
private func getPaypalEmail(onCompletion: ServiceResponse){ private func getPaypalEmail(onCompletion: ServiceResponse){
var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<GetUserPreferencesRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" + "<GetUserPreferencesRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
@ -214,35 +224,10 @@ extension EbayWebServiceManager {
self.requestMaker(soapMessage, theRequest: theRequest) self.requestMaker(soapMessage, theRequest: theRequest)
} }
//used to add images to listing posting request before actually posting
func addImagesToListing(listingID: String, imageURLs: [String], listingOnCompletion: ServiceResponse, body: [String:String],onCompletion: ServiceResponse) { func addImagesToListing(listingID: String, imageURLs: [String], listingOnCompletion: ServiceResponse, body: [String:String],onCompletion: ServiceResponse) {
listItem(body, imageUrls: imageURLs, completion: listingOnCompletion) listItem(body, imageUrls: imageURLs, completion: listingOnCompletion)
/*
var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<ReviseItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
"<RequesterCredentials>" +
"<eBayAuthToken>\(self.xmlResponseDictionary["eBayAuthToken"] as! String)</eBayAuthToken>" +
"</RequesterCredentials>"
soapMessage = soapMessage + "<ErrorLanguage>en_US</ErrorLanguage>" +
"<Item>" +
"<ItemID>\(listingID)</ItemID>"
for i in 0...(imageURLs.count - 1) {
soapMessage = soapMessage + "<PictureDetails>" +
"<PictureURL>\(imageURLs[i].stringByReplacingOccurrencesOfString("&", withString: "&amp;"))</PictureURL>" +
"</PictureDetails>"
}
soapMessage = soapMessage + "</Item></ReviseItemRequest>"
let url = NSURL(string: self.baseURL)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.addValue("ReviseItem", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")
self.completion = onCompletion
self.requestMaker(soapMessage, theRequest: theRequest)
*/
} }
func listItem(params: [String: String], imageUrls: [String], completion: ServiceResponse?){ func listItem(params: [String: String], imageUrls: [String], completion: ServiceResponse?){
@ -254,6 +239,7 @@ extension EbayWebServiceManager {
"<eBayAuthToken>\(self.xmlResponseDictionary["eBayAuthToken"] as! String)</eBayAuthToken>" + "<eBayAuthToken>\(self.xmlResponseDictionary["eBayAuthToken"] as! String)</eBayAuthToken>" +
"</RequesterCredentials>" "</RequesterCredentials>"
//if paypal email not in local cache retrieve it before continuing to post to ebay
if((dict["payment"] as? String) == "PayPal") { if((dict["payment"] as? String) == "PayPal") {
dispatch_group_enter(emailRetrievalGroup) dispatch_group_enter(emailRetrievalGroup)
if((EbayWebServiceManager.settingsDictionary["paypal_email"]) == nil) { if((EbayWebServiceManager.settingsDictionary["paypal_email"]) == nil) {
@ -284,7 +270,8 @@ extension EbayWebServiceManager {
"<PaymentMethods>\(dict["payment"] as! String!)</PaymentMethods>" + "<PaymentMethods>\(dict["payment"] as! String!)</PaymentMethods>" +
"<PayPalEmailAddress>\(dict["paypal_email"] as! String!)</PayPalEmailAddress><PictureDetails><GalleryType>Gallery</GalleryType>" "<PayPalEmailAddress>\(dict["paypal_email"] as! String!)</PayPalEmailAddress><PictureDetails><GalleryType>Gallery</GalleryType>"
for i in 0...(imageUrls.count - 1) { //will replace with actual count once everything is working with images //append image urls to listing request
for i in 0...(imageUrls.count - 1) {
soapMessage = soapMessage + soapMessage = soapMessage +
"<PictureURL>\(imageUrls[i].stringByReplacingOccurrencesOfString("&", withString: "&amp;"))</PictureURL>" "<PictureURL>\(imageUrls[i].stringByReplacingOccurrencesOfString("&", withString: "&amp;"))</PictureURL>"
@ -307,6 +294,8 @@ extension EbayWebServiceManager {
"<Site>US</Site>" + "<Site>US</Site>" +
"</Item></AddItemRequest>" "</Item></AddItemRequest>"
print(soapMessage) print(soapMessage)
//make request
let url = NSURL(string: self.baseURL) let url = NSURL(string: self.baseURL)
let theRequest = NSMutableURLRequest(URL: url!) let theRequest = NSMutableURLRequest(URL: url!)
theRequest.addValue("AddItem", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") theRequest.addValue("AddItem", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")
@ -317,6 +306,7 @@ extension EbayWebServiceManager {
} }
} }
//after getting a sessionID get a unique oauth token
func fetchToken() { func fetchToken() {
let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<FetchTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\"><SessionID>\(self.xmlResponseDictionary["SessionID"] as! String!)</SessionID></FetchTokenRequest>" "<FetchTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\"><SessionID>\(self.xmlResponseDictionary["SessionID"] as! String!)</SessionID></FetchTokenRequest>"
@ -328,10 +318,11 @@ extension EbayWebServiceManager {
self.requestMaker(soapMessage, theRequest: theRequest) self.requestMaker(soapMessage, theRequest: theRequest)
} }
//used to get sub categories when creating a new listing
func getSubCategories(selectedCategory: String, detailLevel: Int, catCode: String, onCompletion: ServiceResponse) { func getSubCategories(selectedCategory: String, detailLevel: Int, catCode: String, onCompletion: ServiceResponse) {
self.isGettingNotification = false self.isGettingNotification = false
self.isGettingSubCategories = true self.isGettingSubCategories = true
//var dict = EbayWebServiceManager.settingsDictionary["categories"]!
var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<GetCategoriesRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" + "<GetCategoriesRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
"<RequesterCredentials>" + "<RequesterCredentials>" +
@ -350,6 +341,7 @@ extension EbayWebServiceManager {
self.requestMaker(soapMessage, theRequest: theRequest) self.requestMaker(soapMessage, theRequest: theRequest)
} }
//used for notifications to retrieve current information about the status of a listing
func getListingInfo(listingID: String, onComplete: ServiceResponse?){ func getListingInfo(listingID: String, onComplete: ServiceResponse?){
var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<GetItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" + "<GetItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
@ -405,6 +397,7 @@ extension EbayWebServiceManager: NSURLConnectionDelegate {
} }
} }
//used to parse xml responses and save data
extension EbayWebServiceManager: NSXMLParserDelegate { extension EbayWebServiceManager: NSXMLParserDelegate {
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
@ -454,23 +447,6 @@ extension EbayWebServiceManager: NSXMLParserDelegate {
"<RequesterCredentials><eBayAuthToken>\(string)</eBayAuthToken>" + "<RequesterCredentials><eBayAuthToken>\(string)</eBayAuthToken>" +
"</RequesterCredentials></GetUserRequest>" "</RequesterCredentials></GetUserRequest>"
/*
*<?xml version="1.0" encoding="utf-8"?>
<GetUserRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<!-- Call-specific Input Fields -->
<IncludeFeatureEligibility> boolean </IncludeFeatureEligibility>
<ItemID> ItemIDType (string) </ItemID>
<UserID> string </UserID>
<!-- Standard Input Fields -->
<DetailLevel> DetailLevelCodeType </DetailLevel>
<!-- ... more DetailLevel values allowed here ... -->
<ErrorLanguage> string </ErrorLanguage>
<MessageID> string </MessageID>
<Version> string </Version>
<WarningLevel> WarningLevelCodeType </WarningLevel>
</GetUserRequest>
*/
let url = NSURL(string: self.baseURL) let url = NSURL(string: self.baseURL)
let theRequest = NSMutableURLRequest(URL: url!) let theRequest = NSMutableURLRequest(URL: url!)
theRequest.addValue("GetUser", forHTTPHeaderField: "X-EBAY-API-CALL-NAME") theRequest.addValue("GetUser", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")
@ -487,6 +463,7 @@ extension EbayWebServiceManager: NSXMLParserDelegate {
} }
break break
//saves paypal email from response
case "DefaultPayPalEmailAddress": case "DefaultPayPalEmailAddress":
var dict = (EbayWebServiceManager.settingsDictionary) var dict = (EbayWebServiceManager.settingsDictionary)
dict["paypal_email"] = string dict["paypal_email"] = string
@ -494,6 +471,8 @@ extension EbayWebServiceManager: NSXMLParserDelegate {
NSUserDefaults.standardUserDefaults().setObject(EbayWebServiceManager.settingsDictionary, forKey: "ebaySettings") NSUserDefaults.standardUserDefaults().setObject(EbayWebServiceManager.settingsDictionary, forKey: "ebaySettings")
self.completion(nil, nil) self.completion(nil, nil)
break break
//saves userID from response and gets toplevel ebay categories
case "UserID" : case "UserID" :
if(!self.isGettingNotification) { if(!self.isGettingNotification) {
print(string) print(string)
@ -545,12 +524,6 @@ extension EbayWebServiceManager: NSXMLParserDelegate {
self.currentCategory = string self.currentCategory = string
} }
/* var dict: Dictionary<String, Dictionary<String, AnyObject>> = (EbayWebServiceManager.settingsDictionary["categories"]!) as! Dictionary<String, Dictionary<String, AnyObject>>
dict[string] = ["cat_id": self.catID, "isLeaf": false, "level": self.catLevel]
EbayWebServiceManager.settingsDictionary["categories"] = dict
NSUserDefaults.standardUserDefaults().setObject(EbayWebServiceManager.settingsDictionary, forKey: "ebaySettings")*/
} }
@ -564,7 +537,6 @@ extension EbayWebServiceManager: NSXMLParserDelegate {
dict[self.currentCategory]!["isLeaf"] = true dict[self.currentCategory]!["isLeaf"] = true
} }
else { else {
//@FIXME: breaking here retrieveing subcategories
if (self.catDetailLevel == Int((self.subCategories[self.currentCategory]!["level"] as! String))) { if (self.catDetailLevel == Int((self.subCategories[self.currentCategory]!["level"] as! String))) {
self.subCategories[self.currentCategory]!["isLeaf"] = true self.subCategories[self.currentCategory]!["isLeaf"] = true

View File

@ -37,7 +37,6 @@ class EtsyRESTAPIManager: NSObject {
//User specific class variables //User specific class variables
private var etsyUser: String! private var etsyUser: String!
private var oauthswift: OAuth1Swift! private var oauthswift: OAuth1Swift!
//private let oauthswift = OAuth1Swift(parameters: ["consumerKey":"snbs78qkfy3yqq6yhe6yv49b","consumerSecret":"4sbva4oqb6", "requestTokenUrl": "https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w%20"])
override init(){ override init(){
super.init() super.init()
@ -61,7 +60,8 @@ class EtsyRESTAPIManager: NSObject {
self.oauthswift.client.credential.oauth_token = (oauthDictionary?["token"] as? String!)! self.oauthswift.client.credential.oauth_token = (oauthDictionary?["token"] as? String!)!
self.oauthswift.client.credential.oauth_token_secret = (oauthDictionary?["secret"] as? String!)! self.oauthswift.client.credential.oauth_token_secret = (oauthDictionary?["secret"] as? String!)!
self.sendGETRequest("/taxonomy/categories", /*body: ["oauth_token":(oauthDictionary?["token"] as? String!)!],*/ onCompletion: { //used to get all etsy categories if user is authorized
self.sendGETRequest("/taxonomy/categories", onCompletion: {
(dict, error) -> Void in (dict, error) -> Void in
var resultDictionary = Dictionary<String, AnyObject>() var resultDictionary = Dictionary<String, AnyObject>()
@ -75,6 +75,7 @@ class EtsyRESTAPIManager: NSObject {
}) })
} }
//sets up posting defaults when posting to etsy
if(NSUserDefaults.standardUserDefaults().boolForKey("etsyDefaultsOverriden")) { if(NSUserDefaults.standardUserDefaults().boolForKey("etsyDefaultsOverriden")) {
EtsyRESTAPIManager.settingsDictionary = (NSUserDefaults.standardUserDefaults().objectForKey("etsySettings") as? Dictionary<String, AnyObject>)! EtsyRESTAPIManager.settingsDictionary = (NSUserDefaults.standardUserDefaults().objectForKey("etsySettings") as? Dictionary<String, AnyObject>)!
@ -115,20 +116,7 @@ extension EtsyRESTAPIManager {
oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller) oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller)
/* //start oauth handshake
let authRequest = self.oauthswift.client.makeRequest("https://openapi.etsy.com/v2/oauth/request_token?", method: OAuthSwiftHTTPRequest.Method.GET, parameters: ["scope":"listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w"] , headers: nil)
do{
try authRequest?.makeRequest()
}catch{
(error)
}
*/
/*["scope":"listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w"]*/
self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w", self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w",
success: { success: {
data, response in data, response in
@ -136,9 +124,6 @@ extension EtsyRESTAPIManager {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
//print(response.allHeaderFields)
//print(dataSting)
let json = JSON(data) let json = JSON(data)
print(json) print(json)
print(dataString) print(dataString)
@ -147,8 +132,6 @@ extension EtsyRESTAPIManager {
self.oauthswift!.authorizeWithCallbackURL( NSURL(string: "vendoo://oauth-callback/etsy")!, success: { self.oauthswift!.authorizeWithCallbackURL( NSURL(string: "vendoo://oauth-callback/etsy")!, success: {
credential, response, parameters in credential, response, parameters in
print(credential.oauth_token)
print(credential.oauth_token_secret)
print(response) print(response)
boolResult = false boolResult = false
@ -165,7 +148,7 @@ extension EtsyRESTAPIManager {
//save data to keychain //save data to keychain
//sign oauth token with verifier
self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/access_token", parameters: ["oauth_verifier":(self.oauthswift.client.credential.oauth_verifier)], self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/access_token", parameters: ["oauth_verifier":(self.oauthswift.client.credential.oauth_verifier)],
success: { success: {
data, response in data, response in
@ -175,8 +158,7 @@ extension EtsyRESTAPIManager {
print(response) print(response)
let json1 = JSON(response) let json1 = JSON(response)
print(json1) print(json1)
//print(response.allHeaderFields)
//print(dataSting)
let json = JSON(data) let json = JSON(data)
print(json) print(json)
print(dataString!) print(dataString!)
@ -197,7 +179,7 @@ extension EtsyRESTAPIManager {
} }
print(matches) print(matches)
//save oauth credentials for current user
let oauth: Dictionary<String, AnyObject!>? = [ "token" : String(matches[1].characters.dropFirst()) , "secret" : String(matches[3].characters.dropFirst()) ] let oauth: Dictionary<String, AnyObject!>? = [ "token" : String(matches[1].characters.dropFirst()) , "secret" : String(matches[3].characters.dropFirst()) ]
do{ do{
@ -210,6 +192,9 @@ extension EtsyRESTAPIManager {
self.oauthswift.client.credential.oauth_token = oauth!["token"]! as! String self.oauthswift.client.credential.oauth_token = oauth!["token"]! as! String
self.oauthswift.client.credential.oauth_token_secret = oauth!["secret"]! as! String self.oauthswift.client.credential.oauth_token_secret = oauth!["secret"]! as! String
// get required credentials from users account to allow posting of new listings
//get user name
self.oauthswift!.client.get("https://openapi.etsy.com/v2/users/__SELF__", self.oauthswift!.client.get("https://openapi.etsy.com/v2/users/__SELF__",
success: { success: {
data, response in data, response in
@ -227,12 +212,14 @@ extension EtsyRESTAPIManager {
onComplete(nil,nil) onComplete(nil,nil)
//get users payment template if one exists, if not create one for user
self.sendGETRequest("/private/shops/__SELF__/payment_templates", onCompletion: { self.sendGETRequest("/private/shops/__SELF__/payment_templates", onCompletion: {
(data, error) -> Void in (data, error) -> Void in
self.sendGETRequest("/taxonomy/categories", /*body: ["oauth_token":(oauthDictionary?["token"] as? String!)!],*/ onCompletion: { self.sendGETRequest("/taxonomy/categories", onCompletion: {
(dict, error) -> Void in (dict, error) -> Void in
//save retrieved categories to settings dictionary
var resultDictionary = Dictionary<String, AnyObject>() var resultDictionary = Dictionary<String, AnyObject>()
for catDictionary in (dict as! [Dictionary<String, AnyObject>]) { for catDictionary in (dict as! [Dictionary<String, AnyObject>]) {
print(catDictionary) print(catDictionary)
@ -245,7 +232,7 @@ extension EtsyRESTAPIManager {
NSUserDefaults.standardUserDefaults().setObject(EtsyRESTAPIManager.settingsDictionary, forKey: "etsySettings") NSUserDefaults.standardUserDefaults().setObject(EtsyRESTAPIManager.settingsDictionary, forKey: "etsySettings")
//retrieve shipping template if one exists, if not create one
self.sendGETRequest("/private/users/__SELF__/shipping/templates", onCompletion: nil) self.sendGETRequest("/private/users/__SELF__/shipping/templates", onCompletion: nil)
}) })
@ -268,19 +255,12 @@ extension EtsyRESTAPIManager {
} }
/*let results = regex.matchesInString(dataString! as String,
options: [], range: NSMakeRange(0, nsString.length))
print(results.map { nsString.substringWithRange($0.range)})*/
} catch let error as NSError { } catch let error as NSError {
print("invalid regex: \(error.localizedDescription)") print("invalid regex: \(error.localizedDescription)")
} }
/*
*/
}, },
failure: { failure: {
@ -289,14 +269,9 @@ extension EtsyRESTAPIManager {
}) })
//return boolResult
}) })
}) })
//getting error here when trying to retrieve the login url from the response
//var dataDictionary = self.convertStringToDictionary(dataString! as String)
//print(dataDictionary!["login_url"])
} }
, failure: { error in , failure: { error in
print(error) print(error)
@ -308,27 +283,12 @@ extension EtsyRESTAPIManager {
} }
//once everything is authorized save true value to the authorization boolean
/*
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "etsyAuthorized")
self.isAuthorized = NSUserDefaults.standardUserDefaults().boolForKey("etsyAuthorized")
*/
} }
func deAuthorizeApp(viewcontroller: UIViewController){ func deAuthorizeApp(viewcontroller: UIViewController){
oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller) oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller)
oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w", oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w",
success: { success: {
@ -337,12 +297,6 @@ extension EtsyRESTAPIManager {
print(dataString!) print(dataString!)
print(response) print(response)
//getting error here when trying to retrieve the login url from the response
//var dataDictionary = self.convertStringToDictionary(dataString! as String)
//print(dataDictionary!["login_url"])
} }
, failure: { error in , failure: { error in
print(error) print(error)
@ -409,7 +363,7 @@ extension EtsyRESTAPIManager {
//MARK: - Request Methods //MARK: - Request Methods
extension EtsyRESTAPIManager { extension EtsyRESTAPIManager {
//the following functions are attempts to get image upload working for etsy
func sendFile( func sendFile(
urlPath:String, urlPath:String,
fileName:String, fileName:String,
@ -442,10 +396,7 @@ extension EtsyRESTAPIManager {
queue: queue, queue: queue,
completionHandler:completionHandler) completionHandler:completionHandler)
} }
// this is a very verbose version of that function
// you can shorten it, but i left it as-is for clarity
// and as an example
func photoDataToFormData(data:NSData,boundary:String,fileName:String) -> NSData { func photoDataToFormData(data:NSData,boundary:String,fileName:String) -> NSData {
var fullData = NSMutableData() var fullData = NSMutableData()
@ -486,42 +437,8 @@ extension EtsyRESTAPIManager {
return fullData return fullData
} }
func generateUserRequest(etsyName: String!, etsyOptions: [String]!) -> String {
//starting url for user request to api
var userRequest: String!
if(etsyName == nil || etsyName == ""){
userRequest = (baseURL + "/private/users/etsystore?")
}
else{
userRequest = (baseURL + "/private/users/" + etsyName + "?")
}
//final api request
return userRequest + "api_key=" + self.apiKey
}
func generateListingRequest(etsyListing: String!){
//starting url for listing request
}
//sends the pregenerated url as a request to api service //sends the pregenerated url as a request to api service
func sendGETRequest(request: String, onCompletion: ServiceResponse?) { 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()*/
self.oauthswift.client.get(self.baseURL + request, self.oauthswift.client.get(self.baseURL + request,
success: { success: {
@ -534,6 +451,7 @@ extension EtsyRESTAPIManager {
switch (request) { switch (request) {
case "/private/shops/__SELF__/payment_templates" : case "/private/shops/__SELF__/payment_templates" :
//create a payment template if none is found
if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) { if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) {
//@TODO: Put payment template parameters in function call //@TODO: Put payment template parameters in function call
self.oauthswift.client.post(self.baseURL + "/private/shops/__SELF__/payment_templates", self.oauthswift.client.post(self.baseURL + "/private/shops/__SELF__/payment_templates",
@ -560,11 +478,13 @@ extension EtsyRESTAPIManager {
onCompletion!(nil,nil) onCompletion!(nil,nil)
} }
break break
case "/private/users/__SELF__/shipping/templates" : case "/private/users/__SELF__/shipping/templates" :
var dict2 = (dict!["results"] as! [[String : AnyObject]]) var dict2 = (dict!["results"] as! [[String : AnyObject]])
if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) { if ((dict!["results"]!.isKindOfClass(NSNull.classForCoder()))) {
//@TODO: Put payment template parameters in function call
//create default shipping template if none found
self.oauthswift.client.post(self.baseURL + "/private/shipping/templates", self.oauthswift.client.post(self.baseURL + "/private/shipping/templates",
parameters: [ parameters: [
"title":"vendoo_default", "title":"vendoo_default",
@ -593,6 +513,8 @@ extension EtsyRESTAPIManager {
} }
break break
//gets etsy categories
case "/taxonomy/categories": case "/taxonomy/categories":
var dict2 = (dict!["results"] as! [[String : AnyObject]]) var dict2 = (dict!["results"] as! [[String : AnyObject]])
onCompletion!(dict2, nil) onCompletion!(dict2, nil)
@ -635,6 +557,8 @@ extension EtsyRESTAPIManager {
//sends the pregenerated url as a request to api service //sends the pregenerated url as a request to api service
func sendPOSTRequest(request: String, var body: [String: AnyObject]?, onCompletion: ServiceResponse?) { func sendPOSTRequest(request: String, var body: [String: AnyObject]?, onCompletion: ServiceResponse?) {
//attempt to post images to etsy
/* let request = NSMutableURLRequest(URL: NSURL(string: request)!) /* let request = NSMutableURLRequest(URL: NSURL(string: request)!)
// Set the method to POST // Set the method to POST
@ -660,6 +584,7 @@ extension EtsyRESTAPIManager {
onCompletion(nil, nil) onCompletion(nil, nil)
}*/ }*/
//for posting image to etsy, currently not working
if(request.containsString("listings/") && request.containsString("/images")){ if(request.containsString("listings/") && request.containsString("/images")){
let url = NSURL(string: self.baseURL + request)! let url = NSURL(string: self.baseURL + request)!
@ -680,6 +605,8 @@ extension EtsyRESTAPIManager {
} }
) )
//more attempts to get image uploads to etsy to work :-(
/* /*
let requested = NSMutableURLRequest(URL: url) let requested = NSMutableURLRequest(URL: url)
requested.HTTPMethod = "POST" requested.HTTPMethod = "POST"
@ -814,6 +741,8 @@ extension EtsyRESTAPIManager {
case "/private/shipping/templates": case "/private/shipping/templates":
break break
//save new listing id from new esty posting
case "/private/listings": case "/private/listings":
var dict2 = (dict!["results"] as! [[String : AnyObject]]) var dict2 = (dict!["results"] as! [[String : AnyObject]])
print(((dict2[0]["listing_id"])!)) print(((dict2[0]["listing_id"])!))
@ -835,7 +764,6 @@ extension EtsyRESTAPIManager {
case "/private/listings": case "/private/listings":
print(error.userInfo["Response-Body"]) print(error.userInfo["Response-Body"])
if((error.userInfo["Response-Body"]!.isEqualToString("price is below listing fee."))) { 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 break
@ -857,6 +785,7 @@ extension EtsyRESTAPIManager {
//MARK: - JSON Methods //MARK: - JSON Methods
extension EtsyRESTAPIManager { extension EtsyRESTAPIManager {
//converts responses from etsy to JSON dictionaries
func convertStringToDictionary(text: String) -> [String:AnyObject]? { func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do { do {

View File

@ -8,6 +8,7 @@
import UIKit import UIKit
/// Used to both display and change options for posting to etsy
class EtsySettingsViewController: UIViewController { class EtsySettingsViewController: UIViewController {
var wereDefaultsChanged: Bool = NSUserDefaults.standardUserDefaults().boolForKey("etsyDefaultsOverriden") var wereDefaultsChanged: Bool = NSUserDefaults.standardUserDefaults().boolForKey("etsyDefaultsOverriden")

View File

@ -18,12 +18,7 @@ protocol FacebookGraphAPIManagerDelegate {
func listingUploadedFB(fbID: String) func listingUploadedFB(fbID: String)
} }
/*
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 { class FacebookGraphAPIManager: NSObject {
//API Manager class variables //API Manager class variables
@ -52,7 +47,6 @@ class FacebookGraphAPIManager: NSObject {
let dictionary = Locksmith.loadDataForUserAccount(self.userEmail, inService: "vendoo") let dictionary = Locksmith.loadDataForUserAccount(self.userEmail, inService: "vendoo")
print("account credentials loaded") print("account credentials loaded")
//print((NSUserDefaults.standardUserDefaults().objectForKey("") as? FBSDKAccessToken!))
} }
} }

View File

@ -2,7 +2,6 @@
// FirebaseService.swift // FirebaseService.swift
// Vendoo // Vendoo
// //
// This class is responsible for initializing a new user, as well as managing web request to both firebase database and data storage
// Created by Okechi Onyeje on 6/2/16. // Created by Okechi Onyeje on 6/2/16.
// Copyright © 2016 Okechi Onyeje. All rights reserved. // Copyright © 2016 Okechi Onyeje. All rights reserved.
// //
@ -13,9 +12,11 @@ import Locksmith
import FirebaseStorage import FirebaseStorage
import TYMActivityIndicatorView import TYMActivityIndicatorView
/// This class is responsible for initializing a new user, as well as managing web request to both firebase database and data storage
class FirebaseManager: NSObject { class FirebaseManager: NSObject {
let ref = FIRDatabase.database().reference() let ref = FIRDatabase.database().reference()
let user_email = ((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!).stringByReplacingOccurrencesOfString(".", withString: "_") let user_email = ((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!).stringByReplacingOccurrencesOfString(".", withString: "_")
let storage = FIRStorage.storage() let storage = FIRStorage.storage()
@ -27,11 +28,12 @@ class FirebaseManager: NSObject {
override init(){ override init(){
super.init() super.init()
indicator.color = UIColor.blueColor() indicator.color = UIColor.blueColor()
//check if user has been created //check if user has been created
dispatch_group_enter(self.firGroup) dispatch_group_enter(self.firGroup)
self.ref.child("Users").observeSingleEventOfType(.Value, withBlock: { snapshot in self.ref.child("Users").observeSingleEventOfType(.Value, withBlock: { snapshot in
// do some stuff once
//if user created, setup user's firebase directory for use with app
if(!snapshot.hasChild(self.user_email)){ if(!snapshot.hasChild(self.user_email)){
let user = ["name": (NSUserDefaults.standardUserDefaults().objectForKey("name") as? String)!, "user_Listings": "", "listing_Keys": "", "favorite_listings_keys": ""] let user = ["name": (NSUserDefaults.standardUserDefaults().objectForKey("name") as? String)!, "user_Listings": "", "listing_Keys": "", "favorite_listings_keys": ""]
self.ref.child("Users").child(self.user_email).setValue(user, withCompletionBlock: { self.ref.child("Users").child(self.user_email).setValue(user, withCompletionBlock: {

View File

@ -8,24 +8,35 @@
import UIKit import UIKit
/// This class is resonsible for retrieving all listing information for the current user.
/// Acts as the tab bar controller for entire application.
/// Responsible for retrieving notifications from each currently authorized network
class HomeViewController: UITabBarController { class HomeViewController: UITabBarController {
//acts as RESTful api call manager for etsy
//call this from tabbar controller to use etsy REST calls //Web Service Managers
let etsyManager: EtsyRESTAPIManager = EtsyRESTAPIManager() let etsyManager: EtsyRESTAPIManager = EtsyRESTAPIManager()
let fbGraphManager = FacebookGraphAPIManager() let fbGraphManager = FacebookGraphAPIManager()
let firebaseManager = FirebaseManager() let firebaseManager = FirebaseManager()
let ebayGraphManager = EbayWebServiceManager() let ebayGraphManager = EbayWebServiceManager()
//Retrieved Listing Variables for draft, current, ended, sold
var userListings: [Listing] = [] var userListings: [Listing] = []
var endedListings: [Listing] = [] var endedListings: [Listing] = []
var soldListings: [Listing] = [] var soldListings: [Listing] = []
//notification manager variables
var notificationsManager = ServiceNotificationManager() var notificationsManager = ServiceNotificationManager()
var notifications: [Dictionary<String, AnyObject>] = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? [] : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>])) var notifications: [Dictionary<String, AnyObject>] = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? [] : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>]))
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
//initialize notifications manager
ServiceNotificationManager.delegate = self ServiceNotificationManager.delegate = self
self.notificationsManager.setManagers(fbGraphManager, fireManager: firebaseManager, ebayManager: ebayGraphManager, etsyManager: etsyManager) self.notificationsManager.setManagers(fbGraphManager, fireManager: firebaseManager, ebayManager: ebayGraphManager, etsyManager: etsyManager)
// Do any additional setup after loading the view. // Do any additional setup after loading the view.
dispatch_group_notify(self.firebaseManager.firGroup, dispatch_get_main_queue(), { dispatch_group_notify(self.firebaseManager.firGroup, dispatch_get_main_queue(), {
@ -37,11 +48,11 @@ class HomeViewController: UITabBarController {
let listingDict = userDict!["user_Listings"] as? [String : AnyObject] let listingDict = userDict!["user_Listings"] as? [String : AnyObject]
//sync notifications //sync notifications (syncs only the notifications for networks that are currently authorized)
if userDict!["notifications"] != nil { if userDict!["notifications"] != nil {
self.notifications = [] self.notifications = []
for (_, v) in userDict!["notifications"] as! [String : AnyObject] { for (_, v) in userDict!["notifications"] as! [String : AnyObject] {
if v["seen"] as! Bool == false/*add network visibility as well*/{ if v["seen"] as! Bool == false{
var is_networkAuth = false var is_networkAuth = false
switch((v["network"] as! String)){ switch((v["network"] as! String)){
case "ebay": case "ebay":
@ -69,18 +80,23 @@ class HomeViewController: UITabBarController {
NSUserDefaults.standardUserDefaults().setObject(userDict!["name"] as? String, forKey: "name") NSUserDefaults.standardUserDefaults().setObject(userDict!["name"] as? String, forKey: "name")
//check if user has any listings to track for notifications
if listingDict != nil { if listingDict != nil {
var notificationStartTracker = 0 var notificationStartTracker = 0 //number used to indicate when to start retrieving notifications
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
//let notificationStartGroup = dispatch_group_create()
for (key, values) in listingDict! { for (key, values) in listingDict! {
//use this too make sure all listings are retrieved before showing listings in ItemsTableView
let serviceGroup: dispatch_group_t = dispatch_group_create() let serviceGroup: dispatch_group_t = dispatch_group_create()
//dispatch_group_enter(notificationStartGroup)
self.firebaseManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in self.firebaseManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
let databaseDict = snapshot.value as! [String : AnyObject] let databaseDict = snapshot.value as! [String : AnyObject]
let storageRef = self.firebaseManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!) let storageRef = self.firebaseManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
//Get Main image first
let mainListingImage = storageRef.child("images/\(key)/main.jpg") let mainListingImage = storageRef.child("images/\(key)/main.jpg")
@ -88,14 +104,17 @@ class HomeViewController: UITabBarController {
mainListingImage.dataWithMaxSize(10 * 1024 * 1024, completion: { mainListingImage.dataWithMaxSize(10 * 1024 * 1024, completion: {
(dataMain, error) -> Void in (dataMain, error) -> Void in
//for the case when there are connectivity issues, allows app to continue without waiting
if(error != nil){ if(error != nil){
print("problem retrieving items") print("problem retrieving items")
notificationStartTracker += 1 notificationStartTracker += 1
}else{ }else{
let mainImage = UIImage(data: dataMain!) let mainImage = UIImage(data: dataMain!)
var listingImages: [UIImage] = [mainImage!] var listingImages: [UIImage] = [mainImage!] //set of all images for this listing
var count = 0
var count = 0 //indicates when checking of all supporting images are done
//Get supporting images //Get supporting images
for i in 1...4 { for i in 1...4 {
let supportListingImg1 = storageRef.child("images/\(key)/\(i).jpg") let supportListingImg1 = storageRef.child("images/\(key)/\(i).jpg")
@ -112,21 +131,21 @@ class HomeViewController: UITabBarController {
if(count == 4){ if(count == 4){
dispatch_group_leave(serviceGroup) dispatch_group_leave(serviceGroup)
notificationStartTracker += 1 notificationStartTracker += 1
//dispatch_group_enter(notificationStartGroup)
//dispatch_group_leave(notificationStartGroup)
} }
}) })
} }
//once images have been retrieved create a listing object with the reitrieved information
dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), { dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), {
print(listingImages.count) print(listingImages.count)
let listingInfo = values as? [String : AnyObject] let listingInfo = values as? [String : AnyObject]
//if no Listing status found then the listing is either active or a draft
if listingInfo!["listingStatus"] == nil { if listingInfo!["listingStatus"] == nil {
self.userListings.append( self.userListings.append(
Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!, Listing(
itemTitle: (listingInfo!["listingTitle"] as? String)!,
itemCategory: listingInfo!["listingCategory"] as? String, itemCategory: listingInfo!["listingCategory"] as? String,
itemQuantity: (listingInfo!["listingQuantity"] as? String)!, itemQuantity: (listingInfo!["listingQuantity"] as? String)!,
itemPrice: listingInfo!["listingPrice"] as? String, itemPrice: listingInfo!["listingPrice"] as? String,
@ -137,6 +156,7 @@ class HomeViewController: UITabBarController {
networksSellingOn: (listingInfo!["networks"] as? Dictionary<String, Bool>)! networksSellingOn: (listingInfo!["networks"] as? Dictionary<String, Bool>)!
)) ))
} }
//create ended Listing objects
else if listingInfo!["listingStatus"] as? String == "Ended" { else if listingInfo!["listingStatus"] as? String == "Ended" {
self.endedListings.append( self.endedListings.append(
Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!, Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!,
@ -150,6 +170,7 @@ class HomeViewController: UITabBarController {
networksSellingOn: (listingInfo!["networks"] as? Dictionary<String, Bool>)! networksSellingOn: (listingInfo!["networks"] as? Dictionary<String, Bool>)!
)) ))
} }
//create sold Listing object
else if listingInfo!["listingStatus"] as? String == "Sold" { else if listingInfo!["listingStatus"] as? String == "Sold" {
self.soldListings.append( self.soldListings.append(
Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!, Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!,
@ -165,16 +186,12 @@ class HomeViewController: UITabBarController {
} }
print(notificationStartTracker) print(notificationStartTracker)
//once all listings have been retrieved and processed start retrieving possible notifications
if(notificationStartTracker == listingDict?.count){ if(notificationStartTracker == listingDict?.count){
NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil) NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil)
self.notificationsManager.setListings(self.userListings) self.notificationsManager.setListings(self.userListings)
self.notificationsManager.startServicePolling() self.notificationsManager.startServicePolling()
/*self.notificationsManager.startServicePolling({
(_,_) -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil)
})*/
} }
@ -193,14 +210,7 @@ class HomeViewController: UITabBarController {
} }
/*
dispatch_group_notify(notificationStartGroup, dispatch_get_main_queue(), {
})*/
}) })
}else { }else {
NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil) NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil)
@ -237,9 +247,10 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
} }
func listingHasStartedRetrievingNotifications() { func listingHasStartedRetrievingNotifications() {
//can be iterated upon to do work when notification retrieval process starts
} }
//delegate method that is used to add notifications to global notifications set
func listingHasEnded(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) { func listingHasEnded(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) {
var notificationArray: [[String: AnyObject]] = self.notifications var notificationArray: [[String: AnyObject]] = self.notifications
@ -269,25 +280,18 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
notificationArray.append( notificationArray.append(
notification as! [String : AnyObject] notification as! [String : AnyObject]
) )
//Move listing from active to ended on local system
self.endedListings.appendContentsOf( self.userListings.filter({$0.key == ((ebayInfo as! [String : AnyObject])["listingKey"] as! String)})) self.endedListings.appendContentsOf( self.userListings.filter({$0.key == ((ebayInfo as! [String : AnyObject])["listingKey"] as! String)}))
self.userListings = self.userListings.filter({$0.key != ((ebayInfo as! [String : AnyObject])["listingKey"] as! String)}) self.userListings = self.userListings.filter({$0.key != ((ebayInfo as! [String : AnyObject])["listingKey"] as! String)})
let itemsView = self.viewControllers![0] as! ItemTableViewController let itemsView = self.viewControllers![0] as! ItemTableViewController
/*self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(((ebayInfo as! [String : AnyObject])["listingKey"] as! String))").observeSingleEventOfType( .Value, withBlock: { //Move listing from active to ended and save new notifications to Firebase
(snapshot) -> Void in
var listingDict = snapshot.value as? [String : AnyObject]
listingDict!["listingStatus"] = "Ended"
self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(((ebayInfo as! [String : AnyObject])["listingKey"] as! String))").setValue(listingDict)
itemsView.itemTable.reloadData()
})*/
self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeSingleEventOfType( .Value, withBlock: { self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeSingleEventOfType( .Value, withBlock: {
(snapshot) -> Void in (snapshot) -> Void in
var userDict = snapshot.value as? [String : AnyObject] var userDict = snapshot.value as? [String : AnyObject]
var notifications = userDict!["notifications"] as? [String: AnyObject] var notifications = userDict!["notifications"] as? [String: AnyObject] //get the current notifications from firebase
if notifications == nil { if notifications == nil {
userDict!["notifications"] = [((ebayInfo as! [String : AnyObject])["listingKey"] as! String):notification] userDict!["notifications"] = [((ebayInfo as! [String : AnyObject])["listingKey"] as! String):notification]
@ -343,10 +347,13 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
notificationArray.append( notificationArray.append(
notification as! [String : AnyObject] notification as! [String : AnyObject]
) )
//Move listing from active to ended on local system
self.endedListings.appendContentsOf( self.userListings.filter({$0.key == ((etsyInfo as! [String : AnyObject])["listingKey"] as! String)})) self.endedListings.appendContentsOf( self.userListings.filter({$0.key == ((etsyInfo as! [String : AnyObject])["listingKey"] as! String)}))
self.userListings = self.userListings.filter({$0.key != ((etsyInfo as! [String : AnyObject])["listingKey"] as! String)}) self.userListings = self.userListings.filter({$0.key != ((etsyInfo as! [String : AnyObject])["listingKey"] as! String)})
let itemsView = self.viewControllers![0] as! ItemTableViewController let itemsView = self.viewControllers![0] as! ItemTableViewController
//Move listing from active to ended and save new notifications to Firebase
self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeSingleEventOfType( .Value, withBlock: { self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeSingleEventOfType( .Value, withBlock: {
(snapshot) -> Void in (snapshot) -> Void in
@ -356,7 +363,7 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
if notifications == nil { if notifications == nil {
userDict!["notifications"] = [((etsyInfo as! [String : AnyObject])["listingKey"] as! String):notification] userDict!["notifications"] = [((etsyInfo as! [String : AnyObject])["listingKey"] as! String):notification]
}else { }else {
notifications![((etsyInfo as! [String : AnyObject])["listingKey"] as! String)] = notification notifications![((etsyInfo as! [String : AnyObject])["listingKey"] as! String)] = notification //get the current notifications from firebase
userDict!["notifications"] = notifications userDict!["notifications"] = notifications
} }
@ -383,6 +390,7 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
} }
//delegate function called mostly by facebook notification when a new comment is posted
func listingHasNewNotifications(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) { func listingHasNewNotifications(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) {
var notificationArray: [Dictionary<String, AnyObject>] = self.notifications var notificationArray: [Dictionary<String, AnyObject>] = self.notifications
@ -395,6 +403,7 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
var userDict = snapshot.value as? [String : AnyObject] var userDict = snapshot.value as? [String : AnyObject]
//check if there are any notifications currently, if not then create a notifications directory in firebase and append notification to it
if (userDict!["notifications"] != nil) { if (userDict!["notifications"] != nil) {
var notificationsFir = userDict!["notifications"] as! [String : AnyObject] var notificationsFir = userDict!["notifications"] as! [String : AnyObject]
notificationsFir[fbInfo!["UUID"] as! String] = fbInfo notificationsFir[fbInfo!["UUID"] as! String] = fbInfo
@ -408,6 +417,8 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
}) })
}else { }else {
//if notification directory already exists append existing notification to it
let id = (fbInfo!["UUID"] as! String) let id = (fbInfo!["UUID"] as! String)
print(id) print(id)
userDict!["notifications"] = ([ id : fbInfo as! [String:AnyObject]]) userDict!["notifications"] = ([ id : fbInfo as! [String:AnyObject]])
@ -459,9 +470,6 @@ extension HomeViewController: ServiceNotificationManagerDelegate {
] ]
) )
} }
//@TODO: add firbase logic to add notifications and delete already viewed notifications
//reload data for notifications
} }
} }

View File

@ -222,20 +222,6 @@ extension Dictionary {
} }
} }
} }
/*
//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 //MARK: - IBActions
extension ListingPreviewViewController { extension ListingPreviewViewController {
@ -273,34 +259,6 @@ extension ListingPreviewViewController {
//save listing to private user path in firebase //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 newListingRef = self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").childByAutoId()
let postingGroup: dispatch_group_t = dispatch_group_create() let postingGroup: dispatch_group_t = dispatch_group_create()
/*if(!(self.networksDictionary["ebay"]!)&&(!(self.networksDictionary["etsy"]!))&&(!(self.networksDictionary["amazon"]!))&&(!(self.networksDictionary["facebook"]!))) {
}else {
dispatch_g
}*/
//post to ebay
/*if(self.networksDictionary["ebay"]!){
dispatch_group_enter(postingGroup)
let body: [String: String] = [ "title": self.itemTitle.text,
"quantity":self.itemQuantity.text,
"description":self.itemDescription.text,
"price":self.itemPrice.text,
"category_id":self.itemListingDictionary["ebaySubCategoryID"] as! String
]
self.ebayManager.listItem(body, completion: {
(listingID, error) -> Void in
if((self.newInProgressListing["networkIDs"] == nil)){
self.newInProgressListing["networkIDs"] = Dictionary<String, AnyObject>()
}
var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary<String, AnyObject>)
networkIDs["ebay"] = listingID as! String
self.newInProgressListing["networkIDs"] = networkIDs
dispatch_group_leave(postingGroup)
})
}*/
//post to amazon //post to amazon
@ -602,7 +560,6 @@ extension ListingPreviewViewController {
//notifies once all selected networks have been posted to //notifies once all selected networks have been posted to
dispatch_group_notify(postingGroup, dispatch_get_main_queue(), { dispatch_group_notify(postingGroup, dispatch_get_main_queue(), {
//self.networksDictionary["areNetworksChosen"] = true
self.newInProgressListing.update(["listingID": newListingRef.key, self.newInProgressListing.update(["listingID": newListingRef.key,
"seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!, "seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!,
"listingTitle": self.itemTitle.text, "listingTitle": self.itemTitle.text,
@ -649,7 +606,7 @@ extension ListingPreviewViewController {
} }
//change code to new multi-image saving //save listing images to firebase
for i in 0...(self.itemListingDictionary["pictures"] as! [UIImageView]).count - 1 { for i in 0...(self.itemListingDictionary["pictures"] as! [UIImageView]).count - 1 {
switch (i) { switch (i) {
@ -704,23 +661,9 @@ extension ListingPreviewViewController {
self.newInProgressListing["networkIDs"] = networkIDs self.newInProgressListing["networkIDs"] = networkIDs
dispatch_group_leave(postingGroup) dispatch_group_leave(postingGroup)
} }
/*self.ebayManager.listItem(body, completion: {
(listingID, error) -> Void in
if((self.newInProgressListing["networkIDs"] == nil)){
self.newInProgressListing["networkIDs"] = Dictionary<String, AnyObject>()
}
var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary<String, AnyObject>)
networkIDs["ebay"] = listingID as! String
self.newInProgressListing["networkIDs"] = networkIDs
dispatch_group_leave(postingGroup)
})*/
self.ebayManager.listItem(body, imageUrls: imageURLs, completion: listingCompletion) self.ebayManager.listItem(body, imageUrls: imageURLs, completion: listingCompletion)
//self.ebayManager.addImagesToListing(networkIDs["ebay"] as! String, imageURLs: imageURLs, listingOnCompletion: listingCompletion, body: body, onCompletion: {
//(_, _) -> Void in
//dispatch_group_leave(postingGroup)
//})
} }
else { else {
dispatch_group_leave(postingGroup) dispatch_group_leave(postingGroup)
@ -761,35 +704,6 @@ extension ListingPreviewViewController {
} }
extension ListingPreviewViewController: UICollectionViewDelegate { extension ListingPreviewViewController: UICollectionViewDelegate {
/*
// 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?) {
}
*/
} }
//Mark: - UICollectionViewDataSource methods //Mark: - UICollectionViewDataSource methods
@ -806,54 +720,11 @@ extension ListingPreviewViewController: UICollectionViewDataSource {
return self.selectedNetworks.count return self.selectedNetworks.count
} }
//used for displaying relevant networks in listing preview
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: NetworkCollectionViewCell! = self.networks.dequeueReusableCellWithReuseIdentifier("network", forIndexPath: indexPath) as! NetworkCollectionViewCell let cell: NetworkCollectionViewCell! = self.networks.dequeueReusableCellWithReuseIdentifier("network", forIndexPath: indexPath) as! NetworkCollectionViewCell
cell.setImg(selectedNetworks[indexPath.row]) cell.setImg(selectedNetworks[indexPath.row])
/*switch (indexPath.row){
case 0:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("ebay", forIndexPath: indexPath)
if(self.networksDictionary["ebay"] == false){
cell.hidden = true
}
else{
cell.hidden = false
}
break
case 1:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("amazon", forIndexPath: indexPath)
if(self.networksDictionary["amazon"] == false){
cell.hidden = true
}
else{
cell.hidden = false
}
break
case 2:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("etsy", forIndexPath: indexPath)
if(self.networksDictionary["etsy"] == false){
cell.hidden = true
}
else{
cell.hidden = false
}
break
default:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("facebook", forIndexPath: indexPath)
if(self.networksDictionary["facebook"] == false){
cell.hidden = true
}
else{
cell.hidden = false
}
break
}*/
return cell return cell
} }

View File

@ -10,6 +10,7 @@ import UIKit
import FirebaseAuth import FirebaseAuth
import Locksmith import Locksmith
/// Used to display options for user, help and legal page, the number of notifications for the user has, and logout capability
class MenuPanelViewController: UIViewController{ class MenuPanelViewController: UIViewController{
var count = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? 0 : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>]).count) var count = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? 0 : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>]).count)
@ -46,41 +47,6 @@ class MenuPanelViewController: UIViewController{
extension MenuPanelViewController: UITableViewDelegate extension MenuPanelViewController: UITableViewDelegate
{ {
/*
// 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
}
*/
} }
extension MenuPanelViewController: UITableViewDataSource extension MenuPanelViewController: UITableViewDataSource
@ -100,6 +66,8 @@ extension MenuPanelViewController: UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell let cell: UITableViewCell
switch(indexPath.row){ switch(indexPath.row){
//display user name and email
case 0: case 0:
cell = (self.table.dequeueReusableCellWithIdentifier("User_Cell", forIndexPath: indexPath) as! UserCell) cell = (self.table.dequeueReusableCellWithIdentifier("User_Cell", forIndexPath: indexPath) as! UserCell)
@ -107,20 +75,30 @@ extension MenuPanelViewController: UITableViewDataSource
(cell as! UserCell).name.text = "Hi " + (NSUserDefaults.standardUserDefaults().objectForKey("name") as? String)! (cell as! UserCell).name.text = "Hi " + (NSUserDefaults.standardUserDefaults().objectForKey("name") as? String)!
(cell as! UserCell).email.text = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)! (cell as! UserCell).email.text = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!
break break
//display notification count
case 1: case 1:
let cellN: Not_TableViewCell! let cellN: Not_TableViewCell!
cellN = self.table.dequeueReusableCellWithIdentifier("Notifications_Cell")! as! Not_TableViewCell cellN = self.table.dequeueReusableCellWithIdentifier("Notifications_Cell")! as! Not_TableViewCell
cellN.count.text = "\(count)" cellN.count.text = "\(count)"
return cellN return cellN
//display settings cell
case 2: case 2:
cell = self.table.dequeueReusableCellWithIdentifier("Settings_Cell")! cell = self.table.dequeueReusableCellWithIdentifier("Settings_Cell")!
break break
//display analytics (next iteration)
case 3: case 3:
cell = self.table.dequeueReusableCellWithIdentifier("Sales_Cell")! cell = self.table.dequeueReusableCellWithIdentifier("Sales_Cell")!
break break
//display FAQ cell
case 4: case 4:
cell = self.table.dequeueReusableCellWithIdentifier("FAQ_Cell")! cell = self.table.dequeueReusableCellWithIdentifier("FAQ_Cell")!
break break
//display how to cell
default: default:
cell = self.table.dequeueReusableCellWithIdentifier("Getting_Started_Cell")! cell = self.table.dequeueReusableCellWithIdentifier("Getting_Started_Cell")!
break break
@ -133,6 +111,7 @@ extension MenuPanelViewController: UITableViewDataSource
extension MenuPanelViewController{ extension MenuPanelViewController{
//logout user and deauthorize all accounts
@IBAction func logoutUser(sender: AnyObject) { @IBAction func logoutUser(sender: AnyObject) {
do{ do{
@ -159,7 +138,8 @@ extension MenuPanelViewController{
(error) (error)
print(error) print(error)
} }
//remove saved information from local cache
for key in Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys) { for key in Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys) {
NSUserDefaults.standardUserDefaults().removeObjectForKey(key) NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
} }

View File

@ -43,11 +43,6 @@ class NetworksTableViewController: UIViewController {
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
// 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()
self.tableView.delegate = self self.tableView.delegate = self
self.tableView.dataSource = self self.tableView.dataSource = self
if(!networkToggleOrSelect){ if(!networkToggleOrSelect){
@ -259,29 +254,6 @@ extension NetworksTableViewController: UITableViewDataSource {
break break
} }
/*switch (indexPath.row){
case 0:
//loads network cell for ebay
cell = (self.tableView.dequeueReusableCellWithIdentifier("ebay", forIndexPath: indexPath) as! EbayTableViewCell)
break
case 1:
//loads network cell for amazon
cell = (self.tableView.dequeueReusableCellWithIdentifier("amazon", forIndexPath: indexPath) as! AmazonTableViewCell)
break
case 2:
//loads network cell for etsy
cell = (self.tableView.dequeueReusableCellWithIdentifier("etsy", forIndexPath: indexPath) as! EtsyTableViewCell)
break
default:
//loads network cell for facebook
cell = (self.tableView.dequeueReusableCellWithIdentifier("facebook", forIndexPath: indexPath) as! FBTableViewCell)
break
}*/
} }
else{ else{
@ -297,7 +269,6 @@ extension NetworksTableViewController: UITableViewDataSource {
(cell as! EbayTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal) (cell as! EbayTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal)
}) })
//(cell as! EbayTableViewCell).networkToggle.setOn(true, animated: false)
}else{ }else{
(cell as! EbayTableViewCell).settingsBtn.enabled = false (cell as! EbayTableViewCell).settingsBtn.enabled = false
(cell as! EbayTableViewCell).settingsBtn.hidden = true (cell as! EbayTableViewCell).settingsBtn.hidden = true
@ -317,7 +288,6 @@ extension NetworksTableViewController: UITableViewDataSource {
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
(cell as! EtsyTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal) (cell as! EtsyTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal)
//(cell as! EtsyTableViewCell).networkToggle.setOn(true, animated: false)
}) })
}else{ }else{
@ -334,7 +304,6 @@ extension NetworksTableViewController: UITableViewDataSource {
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
(cell as! FBTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal) (cell as! FBTableViewCell).authorizeBtn.setTitle("Logout", forState: UIControlState.Normal)
}) })
//(cell as! FBTableViewCell).networkToggle.setOn(true, animated: false)
}else{ }else{
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
(cell as! FBTableViewCell).settingsBtn.enabled = false (cell as! FBTableViewCell).settingsBtn.enabled = false
@ -346,11 +315,6 @@ extension NetworksTableViewController: UITableViewDataSource {
} }
} }
// Configure the cell (in this case show or hide the cell depending on which network the item is being listed on)
return cell return cell
} }
} }
@ -483,7 +447,6 @@ extension NetworksTableViewController: UITableViewDelegate {
cell.setSelected(false, animated: false) cell.setSelected(false, animated: false)
//selection code for ebay //selection code for ebay
//print(cell.networkToggle.on)
if(cell.networkToggle.on){ if(cell.networkToggle.on){
@ -561,15 +524,6 @@ extension NetworksTableViewController: UITableViewDelegate {
}) })
//code to select network //code to select network
self.networksDictionary["etsy"] = true self.networksDictionary["etsy"] = true
//this is the type of code desired to access the rest management classes
/*
let tabBar = self.tabBarController
(tabBar as? HomeViewController)?.etsyManager.authorizeApp(self)
*/
} }
break break
@ -609,208 +563,29 @@ extension NetworksTableViewController: UITableViewDelegate {
} }
else{ else{}
/*
//case where class is being used to authorize a network for the app to post on
switch (indexPath.row){
case 0:
let cell: EbayTableViewCell!
cell = (self.tableView.dequeueReusableCellWithIdentifier("ebay", forIndexPath: indexPath) as! EbayTableViewCell)
cell.setSelected(false, animated: false)
/*OAuthorization code for ebay*/
print(cell.networkToggle.on)
if(((self.tabBarController as? HomeViewController)?.ebayGraphManager.isAuthorized)!){
//code to deauthorize network
cell.networkToggle.setOn(false, animated: true)
let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.ebayGraphManager.deauthorizeApp())!
cell.networkToggle.on = ((tabBar as? HomeViewController)?.ebayGraphManager.isAuthorized)!
}
else{
//code to authorize network
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(true, animated: true)
})
let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.ebayGraphManager.authorizeApp())!
cell.networkToggle.on = ((tabBar as? HomeViewController)?.ebayGraphManager.isAuthorized)!
}
break
case 1:
let cell: AmazonTableViewCell!
cell = (self.tableView.dequeueReusableCellWithIdentifier("amazon", forIndexPath: indexPath) as! AmazonTableViewCell)
cell.setSelected(false, animated: false)
//OAuthorization code for amazon
if(cell.networkToggle.on == true){
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(false, animated: true)
})
//code to deauthorize network
}
else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(true, animated: true)
})
//code to authorize network
}
break
case 2:
let cell: EtsyTableViewCell!
cell = (self.tableView.dequeueReusableCellWithIdentifier("etsy", forIndexPath: indexPath) as! EtsyTableViewCell)
cell.setSelected(false, animated: false)
//OAuthorization code for etsy
if(((self.tabBarController as? HomeViewController)?.etsyManager.isAuthorized)!){
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(false, animated: true)
})
//code to deauthorize network
let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.etsyManager.deAuthorizeApp(self))!
cell.networkToggle.on = ((tabBar as? HomeViewController)?.etsyManager.isAuthorized)!
}
else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(true, animated: true)
})
//code to authorize network
//this is the type of code desired to access the rest management classes
let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.etsyManager.authorizeApp(self))!
cell.networkToggle.on = ((tabBar as? HomeViewController)?.etsyManager.isAuthorized)!
//self.etsyManager.authorizeApp(self)
}
break
default:
let cell: FBTableViewCell!
cell = (self.tableView.dequeueReusableCellWithIdentifier("facebook", forIndexPath: indexPath) as! FBTableViewCell)
cell.setSelected(false, animated: false)
//OAuthorization code for facebook
if((self.tabBarController as? HomeViewController)?.fbGraphManager.isAuthorized)!{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(false, animated: true)
})
//code to deauthorize network
let tabBar = self.tabBarController
let didSucceed:Bool = ((tabBar as? HomeViewController)?.fbGraphManager.deAuthorizeApp(self))!
cell.networkToggle.on = !didSucceed
}
else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.networkToggle.setOn(true, animated: true)
})
//code to authorize network
//this is the type of code desired to access the rest management classes
let tabBar = self.tabBarController
let didSucceed: Bool = ((tabBar as? HomeViewController)?.fbGraphManager.authorizeApp(self))!
cell.networkToggle.on = didSucceed
}
break
}*/
}
} }
/*
// 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
}
*/
} }
extension NetworksTableViewController: EbayWebServiceManagerDelegate { extension NetworksTableViewController: EbayWebServiceManagerDelegate {
//open webview for user to login with ebay
func signInUser(signInString : String!) { func signInUser(signInString : String!) {
let mywebViewController = UIViewController() let mywebViewController = UIViewController()
//let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
let myWebView = UIWebView(frame: mywebViewController.view.bounds) let myWebView = UIWebView(frame: mywebViewController.view.bounds)
myWebView.delegate = self myWebView.delegate = self
myWebView.loadRequest(NSURLRequest(URL: NSURL(string: signInString)!)) myWebView.loadRequest(NSURLRequest(URL: NSURL(string: signInString)!))
mywebViewController.view = myWebView mywebViewController.view = myWebView
let navController = UINavigationController(rootViewController: mywebViewController) let navController = UINavigationController(rootViewController: mywebViewController)
//selector function to dismiss webview
mywebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("dismiss")) mywebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("dismiss"))
self.presentViewController(navController, animated: true, completion: nil) self.presentViewController(navController, animated: true, completion: nil)
//self.view.addSubview(myWebView)
} }
} }
@ -831,7 +606,6 @@ extension NetworksTableViewController: UIWebViewDelegate {
print("Webview did finish load") print("Webview did finish load")
if (webView.request != nil) if (webView.request != nil)
{ {
//print(webView.request?.allHTTPHeaderFields)
var responseString : NSString? = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")! var responseString : NSString? = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")!
if((responseString!.containsString("Authorization successfully completed"))){ if((responseString!.containsString("Authorization successfully completed"))){
NSLog("Oauth successful") NSLog("Oauth successful")
@ -842,24 +616,28 @@ extension NetworksTableViewController: UIWebViewDelegate {
} }
//called when webview is dismissed
func dismiss() { func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil) self.dismissViewControllerAnimated(true, completion: nil)
} }
} }
extension NetworksTableViewController { extension NetworksTableViewController {
@IBAction func toggleAuth(sender: UIButton){ @IBAction func toggleAuth(sender: UIButton){
print(sender.superview!.superview!.classForCoder) print(sender.superview!.superview!.classForCoder)
//Authorize app //Authorize app
if(sender.titleLabel?.text == "Login") { if(sender.titleLabel?.text == "Login") {
//check which network cell was selected to determine which network to perform oauth on
switch (sender.superview?.superview?.classForCoder){ switch (sender.superview?.superview?.classForCoder){
case is EbayTableViewCell.Type: case is EbayTableViewCell.Type:
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.ebayGraphManager.authorizeApp({ ((tabBar as? HomeViewController)?.ebayGraphManager.authorizeApp({
something,_ -> Void in something,_ -> Void in
// // // // switch login button to logout and display settings button once login process is complete
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
sender.setTitle("Logout", forState: UIControlState.Normal) sender.setTitle("Logout", forState: UIControlState.Normal)
(sender.superview?.superview as! EbayTableViewCell).settingsBtn.enabled = true (sender.superview?.superview as! EbayTableViewCell).settingsBtn.enabled = true
@ -874,6 +652,7 @@ extension NetworksTableViewController {
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.etsyManager.authorizeApp(self, onComplete: { ((tabBar as? HomeViewController)?.etsyManager.authorizeApp(self, onComplete: {
something , _ -> Void in something , _ -> Void in
// switch login button to logout and display settings button once login process is complete
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
sender.setTitle("Logout", forState: UIControlState.Normal) sender.setTitle("Logout", forState: UIControlState.Normal)
(sender.superview?.superview as! EtsyTableViewCell).settingsBtn.enabled = true (sender.superview?.superview as! EtsyTableViewCell).settingsBtn.enabled = true
@ -886,6 +665,7 @@ extension NetworksTableViewController {
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.fbGraphManager.authorizeApp(self, onComplete: { ((tabBar as? HomeViewController)?.fbGraphManager.authorizeApp(self, onComplete: {
something , _ -> Void in something , _ -> Void in
// switch login button to logout and display settings button once login process is complete
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
sender.setTitle("Logout", forState: UIControlState.Normal) sender.setTitle("Logout", forState: UIControlState.Normal)
(sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = true (sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = true
@ -906,6 +686,7 @@ extension NetworksTableViewController {
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.ebayGraphManager.deauthorizeApp())! ((tabBar as? HomeViewController)?.ebayGraphManager.deauthorizeApp())!
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
// switch logout button to login and hide settings button once login process is complete
sender.setTitle("Login", forState: UIControlState.Normal) sender.setTitle("Login", forState: UIControlState.Normal)
(sender.superview?.superview as! EbayTableViewCell).settingsBtn.enabled = false (sender.superview?.superview as! EbayTableViewCell).settingsBtn.enabled = false
(sender.superview?.superview as! EbayTableViewCell).settingsBtn.hidden = true (sender.superview?.superview as! EbayTableViewCell).settingsBtn.hidden = true
@ -918,6 +699,7 @@ extension NetworksTableViewController {
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.etsyManager.deAuthorizeApp(self))! ((tabBar as? HomeViewController)?.etsyManager.deAuthorizeApp(self))!
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
// switch logout button to login and hide settings button once login process is complete
sender.setTitle("Login", forState: UIControlState.Normal) sender.setTitle("Login", forState: UIControlState.Normal)
(sender.superview?.superview as! EtsyTableViewCell).settingsBtn.enabled = false (sender.superview?.superview as! EtsyTableViewCell).settingsBtn.enabled = false
(sender.superview?.superview as! EtsyTableViewCell).settingsBtn.hidden = true (sender.superview?.superview as! EtsyTableViewCell).settingsBtn.hidden = true
@ -927,6 +709,7 @@ extension NetworksTableViewController {
let tabBar = self.tabBarController let tabBar = self.tabBarController
((tabBar as? HomeViewController)?.fbGraphManager.deAuthorizeApp(self))! ((tabBar as? HomeViewController)?.fbGraphManager.deAuthorizeApp(self))!
dispatch_async(dispatch_get_main_queue(), { dispatch_async(dispatch_get_main_queue(), {
// switch logout button to login and hide settings button once login process is complete
sender.setTitle("Login", forState: UIControlState.Normal) sender.setTitle("Login", forState: UIControlState.Normal)
(sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = false (sender.superview?.superview as! FBTableViewCell).settingsBtn.enabled = false
(sender.superview?.superview as! FBTableViewCell).settingsBtn.hidden = true (sender.superview?.superview as! FBTableViewCell).settingsBtn.hidden = true

View File

@ -8,6 +8,7 @@
import UIKit import UIKit
/// Responsible for displaying notifications from authorized networks
class NotificationsViewController: UIViewController { class NotificationsViewController: UIViewController {
var notifications: [Dictionary<String, AnyObject>]! = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? [] : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>])) var notifications: [Dictionary<String, AnyObject>]! = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? [] : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, AnyObject>]))
var fireBase = FirebaseManager() var fireBase = FirebaseManager()
@ -45,11 +46,14 @@ extension NotificationsViewController: UITableViewDelegate {
var notification = self.notifications[indexPath.row] var notification = self.notifications[indexPath.row]
switch ( notification["network"] as! String) { switch ( notification["network"] as! String) {
// displays new comments from faebook listings with option of dismissing them
case "facebook": case "facebook":
let alert = UIAlertController(title: "New Comment from \(notification["senderName"] as! String)", message: (notification["commentMessage"] as! String), preferredStyle: .Alert) let alert = UIAlertController(title: "New Comment from \(notification["senderName"] as! String)", message: (notification["commentMessage"] as! String), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: { alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: {
(action) -> Void in (action) -> Void in
//when user marks as dismissed, mark it in firebase DB so it is no longer retrieved by app
notification["seen"] = true notification["seen"] = true
self.notifications[indexPath.row] = notification self.notifications[indexPath.row] = notification
self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: { self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: {
@ -67,11 +71,13 @@ extension NotificationsViewController: UITableViewDelegate {
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: {(action) -> Void in})) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: {(action) -> Void in}))
self.presentViewController(alert, animated: true, completion: nil) self.presentViewController(alert, animated: true, completion: nil)
break break
case "ebay": case "ebay":
let alert = UIAlertController(title: "New Notification", message: "Would you like to dismiss this notification?", preferredStyle: .Alert) let alert = UIAlertController(title: "New Notification", message: "Would you like to dismiss this notification?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: { alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: {
(action) -> Void in (action) -> Void in
//when user marks as dismissed, mark it in firebase DB so it is no longer retrieved by app
notification["seen"] = true notification["seen"] = true
self.notifications[indexPath.row] = notification self.notifications[indexPath.row] = notification
self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: { self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: {
@ -94,6 +100,7 @@ extension NotificationsViewController: UITableViewDelegate {
alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: { alert.addAction(UIAlertAction(title: "Mark as Dismissed", style: .Default, handler: {
(action) -> Void in (action) -> Void in
//when user marks as dismissed, mark it in firebase DB so it is no longer retrieved by app
notification["seen"] = true notification["seen"] = true
self.notifications[indexPath.row] = notification self.notifications[indexPath.row] = notification
self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: { self.fireBase.ref.child("Users/\(self.fireBase.user_email)/notifications/\(notification["UUID"] as! String)").setValue(notification, withCompletionBlock: {
@ -122,6 +129,7 @@ extension NotificationsViewController: UITableViewDelegate {
extension NotificationsViewController: UITableViewDataSource { extension NotificationsViewController: UITableViewDataSource {
//used to display notification title and the image of the market place it belongs too
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: NotificationTableViewCell! = self.notificationTable.dequeueReusableCellWithIdentifier("notification_cell") as! NotificationTableViewCell let cell: NotificationTableViewCell! = self.notificationTable.dequeueReusableCellWithIdentifier("notification_cell") as! NotificationTableViewCell
let notification = self.notifications[indexPath.row] let notification = self.notifications[indexPath.row]

View File

@ -6,7 +6,7 @@
// Copyright © 2016 Okechi Onyeje. All rights reserved. // Copyright © 2016 Okechi Onyeje. All rights reserved.
// //
//NEED TO MAKE ALERT NAVIGATE BACK TO LOGIN ONCE RECOVERY IS SENT //@FIXME: NEED TO MAKE ALERT NAVIGATE BACK TO LOGIN ONCE RECOVERY IS SENT
import UIKit import UIKit
import FirebaseAuth import FirebaseAuth

View File

@ -33,7 +33,9 @@ class ServiceNotificationManager: NSObject {
} }
func startServicePolling() { func startServicePolling() {
//timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: #selector(ServiceNotificationManager.pollServices), userInfo: nil, repeats: true) // notifications can be switched to a set interval by uncommenting the following line and commenting the line below it
//timer = NSTimer.scheduledTimerWithTimeInterval(1800.0, target: self, selector: #selector(ServiceNotificationManager.pollServices), userInfo: nil, repeats: true)
pollServices() pollServices()
} }
@ -53,9 +55,7 @@ class ServiceNotificationManager: NSObject {
} }
func pollServices(){ func pollServices(){
let notificationGroup = dispatch_group_create()
//let notificationEndCount = 0
//dispatch_group_enter(notificationGroup)
for listing in userListings { for listing in userListings {
self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(listing.key)").observeSingleEventOfType( .Value, withBlock: { self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(listing.key)").observeSingleEventOfType( .Value, withBlock: {
@ -71,16 +71,16 @@ class ServiceNotificationManager: NSObject {
let etsyID = (networksDict["etsy"] as? Int) let etsyID = (networksDict["etsy"] as? Int)
let amazonID = (networksDict["amazon"] as? String) let amazonID = (networksDict["amazon"] as? String)
//@TODO: Skeleton for Notfications Manager is set up. Need to implement listing request for each listing to retrieve relevant notifications for user such as if listing has ended
if(ebayID != nil){ if(ebayID != nil){
if self.ebayGraphManager.isAuthorized { if self.ebayGraphManager.isAuthorized {
self.ebayGraphManager.getListingInfo(ebayID!, onComplete: { self.ebayGraphManager.getListingInfo(ebayID!, onComplete: {
(listingNotificationInfo, error) -> Void in (listingNotificationInfo, error) -> Void in
//dispatch_group_leave(notificationGroup)
let info = (listingNotificationInfo as! [String : AnyObject]) let info = (listingNotificationInfo as! [String : AnyObject])
if(info["status"] as! String == "Ended") { if(info["status"] as! String == "Ended") {
if((info["quantitySold"] as! Int) > 0) { if((info["quantitySold"] as! Int) > 0) {
//@TODO: Add both firbase logic and code logic to do notifications for sold listings
//checks if listing is sold out
if (((info["itemQuantity"] as! Int) - (info["quantitySold"] as! Int)) == 0) { if (((info["itemQuantity"] as! Int) - (info["quantitySold"] as! Int)) == 0) {
ServiceNotificationManager.delegate?.listingHasNewNotifications( ServiceNotificationManager.delegate?.listingHasNewNotifications(
@ -113,6 +113,8 @@ class ServiceNotificationManager: NSObject {
} }
if(facebookID != nil){ if(facebookID != nil){
if(self.fbGraphManager.isAuthorized) { if(self.fbGraphManager.isAuthorized) {
//get new comments on a listing post from facebook
self.fbGraphManager.getListingInfo ("/\(facebookID!)/comments", onCompletion: { self.fbGraphManager.getListingInfo ("/\(facebookID!)/comments", onCompletion: {
(listingNotificationInfo, error) -> Void in (listingNotificationInfo, error) -> Void in
@ -173,7 +175,7 @@ class ServiceNotificationManager: NSObject {
let info = (listingNotificationInfo as! [String : AnyObject]) let info = (listingNotificationInfo as! [String : AnyObject])
//@TODO: Test this code with the draft condition for both expired and sold_out //checks for ended unsold listings
if ((info["status"] as! String == "expired") || (info["status"] as! String == "removed")) { if ((info["status"] as! String == "expired") || (info["status"] as! String == "removed")) {
ServiceNotificationManager.delegate?.listingHasEnded( ServiceNotificationManager.delegate?.listingHasEnded(
@ -186,7 +188,7 @@ class ServiceNotificationManager: NSObject {
"listingKey": listing.key] "listingKey": listing.key]
) )
//checks for sold listings
}else if info["status"] as! String == "sold_out" { }else if info["status"] as! String == "sold_out" {
ServiceNotificationManager.delegate?.listingHasNewNotifications( ServiceNotificationManager.delegate?.listingHasNewNotifications(
@ -210,22 +212,16 @@ class ServiceNotificationManager: NSObject {
if(amazonID != nil){ if(amazonID != nil){
} }
//dispatch_group_leave(notificationGroup)
}else { }else {
// dispatch_group_leave(notificationGroup)
} }
}else { }else {
//dispatch_group_leave(notificationGroup)
} }
}) })
} }
//used to turn off notification mode for ebay so that it may operate as a request manager instead of a notification manager
//dispatch_group_notify(notificationGroup, dispatch_get_main_queue(), {
//self.delegate?.listingHasNewNotifications(nil, ebayInfo: nil, amazonInfo: nil, etsyInfo: nil)
//})
self.ebayGraphManager.isGettingNotification = false self.ebayGraphManager.isGettingNotification = false
} }

View File

@ -12,6 +12,7 @@ import FirebaseAuth
import FirebaseDatabase import FirebaseDatabase
import FirebaseStorage import FirebaseStorage
/// This class is responsible for updating current users password and deleting current user account
class SettingsViewController: UIViewController { class SettingsViewController: UIViewController {
//IBOutlet //IBOutlet
@ -107,7 +108,6 @@ extension SettingsViewController: UITableViewDelegate {
let dictionary = Locksmith.loadDataForUserAccount((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!, inService: "vendoo") let dictionary = Locksmith.loadDataForUserAccount((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!, inService: "vendoo")
if(textField1.text == dictionary!["pass"] as? String){ if(textField1.text == dictionary!["pass"] as? String){
//put in password changing code later
print("password accepted please enter new password") print("password accepted please enter new password")
let alert2 = UIAlertController(title: "Change Password", message: "WARNING! You are about to change your vendoo account password. Please enter your new password to continue.", preferredStyle: .Alert) let alert2 = UIAlertController(title: "Change Password", message: "WARNING! You are about to change your vendoo account password. Please enter your new password to continue.", preferredStyle: .Alert)
@ -148,7 +148,6 @@ extension SettingsViewController: UITableViewDelegate {
}else{ }else{
//put in password changing code later
print("incorrect password") print("incorrect password")
let alert2 = UIAlertController(title: "Incorrect Password", message: "Incorrect password. Please try again.", preferredStyle: .Alert) let alert2 = UIAlertController(title: "Incorrect Password", message: "Incorrect password. Please try again.", preferredStyle: .Alert)
@ -184,12 +183,11 @@ extension SettingsViewController: UITableViewDelegate {
let dictionary = Locksmith.loadDataForUserAccount((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!, inService: "vendoo") let dictionary = Locksmith.loadDataForUserAccount((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!, inService: "vendoo")
if(textField.text == dictionary!["pass"] as? String){ if(textField.text == dictionary!["pass"] as? String){
//put in deletion code later
print("account deleted, add in deletion code as well as deauthorization code for any network currently authorized") print("account deleted, add in deletion code as well as deauthorization code for any network currently authorized")
//get all listing information for current user //get all listing information for current user and delete from gloabl listings in firebase
print((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!) print((NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!)
self.firbase.ref.child("Users/\(self.firbase.user_email)").observeSingleEventOfType( .Value, withBlock: { self.firbase.ref.child("Users/\(self.firbase.user_email)").observeSingleEventOfType( .Value, withBlock: {
(snapshot) -> Void in (snapshot) -> Void in
@ -206,7 +204,11 @@ extension SettingsViewController: UITableViewDelegate {
} }
} }
self.firbase.ref.child("Users").child(self.firbase.user_email).removeValueWithCompletionBlock({
//delete all user accounts currently assouciated with user
self.firbase.ref.child("Users").child(self.firbase.user_email).removeValueWithCompletionBlock({
(error, ref) -> Void in (error, ref) -> Void in
if error == nil { if error == nil {
@ -257,7 +259,6 @@ extension SettingsViewController: UITableViewDelegate {
alert.dismissViewControllerAnimated(true, completion: nil) alert.dismissViewControllerAnimated(true, completion: nil)
}else{ }else{
//put in password changing code later
print("incorrect password") print("incorrect password")
let alert2 = UIAlertController(title: "Incorrect Password", message: "Incorrect password. Please try again.", preferredStyle: .Alert) let alert2 = UIAlertController(title: "Incorrect Password", message: "Incorrect password. Please try again.", preferredStyle: .Alert)

View File

@ -6,7 +6,6 @@
// Copyright © 2016 Okechi Onyeje. All rights reserved. // Copyright © 2016 Okechi Onyeje. All rights reserved.
// //
//NEED TO FIX AUTO LOGIN USING KEYCHAIN AND SECURITY FRAMEWORKS, WILL WORK ON LATER
import UIKit import UIKit
import FirebaseAuth import FirebaseAuth
@ -30,6 +29,7 @@ class SignInViewController: UIViewController {
self.email.delegate = self self.email.delegate = self
self.password.delegate = self self.password.delegate = self
//check if there is a user logged in
if NSUserDefaults.standardUserDefaults().boolForKey("signedIn"){ if NSUserDefaults.standardUserDefaults().boolForKey("signedIn"){
//load user account from keychain //load user account from keychain
@ -53,42 +53,77 @@ class SignInViewController: UIViewController {
//IBActions //IBActions
extension SignInViewController { extension SignInViewController {
//sign in current or returning user
@IBAction func signInUser(sender: AnyObject) { @IBAction func signInUser(sender: AnyObject) {
FIRAuth.auth()?.signInWithEmail(email.text!, password: password.text!) { (user, error) in //add validation
if let error = error { let finalEmail = email!.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print(error.localizedDescription)
return if isValidEmail(finalEmail){
} else { FIRAuth.auth()?.signInWithEmail(email.text!, password: password.text!) { (user, error) in
if error != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in //alert for wrong pass
/*If the user has not already signed in then save their log in info*/ if ( error!.userInfo["error_name"] as! String == "ERROR_WRONG_PASSWORD"){
if !(NSUserDefaults.standardUserDefaults().boolForKey("signedIn")){
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "signedIn")
NSUserDefaults.standardUserDefaults().setObject(self.email.text, forKey: "email")
//KeychainWrapper.setObject(self.password.text!, forKey: "password")
//save data to keychain var alert = UIAlertController(title: "Incorrect Password", message: "The password was invalid for the email given, please reenter the correct password.", preferredStyle: .Alert)
do{
try Locksmith.saveData(["pass": self.password.text!], forUserAccount: self.email.text!, inService: "vendoo") alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
print("account credentials saved") }))
} self.presentViewController(alert, animated: true, completion: nil)
catch{
//could not save data to keychain //alert for invalid email
print("account credentials could not be saved") }else if (error!.userInfo["error_name"] as! String == "ERROR_INVALID_EMAIL"){
} var alert = UIAlertController(title: "Email Invalid", message: "The email given was not valid, please enter a valid email.", preferredStyle: .Alert)
print("User saved")
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
//alert for disabled account
}else if (error!.userInfo["error_name"] as! String == "ERROR_USER_DISABLED"){
var alert = UIAlertController(title: "User Account Disabled", message: "Your account has temporarily been disabled, please contact support for more information.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
} }
} else {
//will remove this line of code once dispatch_async(dispatch_get_main_queue(), { () -> Void in
//removes saved user until autologin and security keychain operational
//NSUserDefaults.standardUserDefaults().setBool(false, forKey: "signedIn") /*If the user has not already signed in then save their log in info*/
self.performSegueWithIdentifier("HomeScreenSegue", sender:nil) if !(NSUserDefaults.standardUserDefaults().boolForKey("signedIn")){
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "signedIn")
}) NSUserDefaults.standardUserDefaults().setObject(self.email.text, forKey: "email")
//save data to keychain
do{
try Locksmith.saveData(["pass": self.password.text!], forUserAccount: self.email.text!, inService: "vendoo")
print("account credentials saved")
}
catch{
//could not save data to keychain
print("account credentials could not be saved")
}
print("User saved")
}
self.performSegueWithIdentifier("HomeScreenSegue", sender:nil)
})
}
} }
}else {
//alert for invalid email
let alert = UIAlertController(title: "Bad Email Given", message: "The email given was not valid. Please enter a valid email", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
} }
} }
} }
@ -128,7 +163,20 @@ extension SignInViewController {
//Private Class Helper Methods //Private Class Helper Methods
extension SignInViewController { extension SignInViewController {
//Validate Email/Username
func isValidEmail(testStr:String) -> Bool {
print("Validate emilId: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
} }

View File

@ -6,7 +6,7 @@
// Copyright © 2016 Okechi Onyeje. All rights reserved. // Copyright © 2016 Okechi Onyeje. All rights reserved.
// //
//@FIXME: NEED TO PROMPT NEW USER THAT THEY HAVE BEEN LOGGED IN, NEED TO ADD AN INDICTOR TO LET USER KNOW THEY NEED TO WAIT AND NEED TO SEGUE TO MAIN SCREEN VIEW CONTROLLER //@TODO: NEED TO PROMPT NEW USER THAT THEY HAVE BEEN LOGGED IN, NEED TO ADD AN INDICTOR TO LET USER KNOW THEY NEED TO WAIT AND NEED TO SEGUE TO MAIN SCREEN VIEW CONTROLLER
import UIKit import UIKit
import FirebaseAuth import FirebaseAuth
@ -43,21 +43,47 @@ class SignUpViewController: UIViewController {
//MARK: - IBAction //MARK: - IBAction
extension SignUpViewController { extension SignUpViewController {
//sign up new user
@IBAction func signUpUser(sender: AnyObject) { @IBAction func signUpUser(sender: AnyObject) {
if( (self.email.text != "") && (self.name.text != "") && (self.password.text != "")) { if( (self.email.text != "") && (self.name.text != "") && (self.password.text != "")) { //check for input in all 3 required fields
let finalEmail = email!.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let finalEmail = email!.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if isValidEmail(finalEmail){ if isValidEmail(finalEmail){
FIRAuth.auth()?.createUserWithEmail(email.text!, password: password.text!) { (user, error) in FIRAuth.auth()?.createUserWithEmail(email.text!, password: password.text!) { (user, error) in
if error != nil { if error != nil {
/*
if ( error!.userInfo[("error_name" as NSObject!)] == "ERROR_WEAK_PASSWORD"){ //alert for weak pass
if ( error!.userInfo["error_name"] as! String == "ERROR_WEAK_PASSWORD"){
var alert = UIAlertController(title: "Password too Weak", message: "Please enter a stronger password to complete your sign up process.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
} //alert for in use email
*/ }else if (error!.userInfo["error_name"] as! String == "ERROR_EMAIL_ALREADY_IN_USE"){
var alert = UIAlertController(title: "Email Already in Use", message: "The email provided is already in use, please use a different email.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
//unknown error or error case
}else{
var alert = UIAlertController(title: "Unknown Error", message: "An unknown error has occurred, please try again later.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
}
print("user could not be created") print("user could not be created")
print(error!.localizedDescription) print(error!.localizedDescription)
return return
} }
else{ else{
@ -80,11 +106,20 @@ extension SignUpViewController {
} }
} }
}else{
//alert for invalid email
let alert = UIAlertController(title: "Bad Email Given", message: "The email given was not valid. Please enter a valid email", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
}))
self.presentViewController(alert, animated: true, completion: nil)
} }
//alert for required fields missing
}else { }else {
var alert = UIAlertController(title: "Missing Required Fields", message: "You are missing required field(s) to complete your Vendoo sign up. Please make sure the email, name, and password fields have been filled.", preferredStyle: .Alert) let alert = UIAlertController(title: "Missing Required Fields", message: "You are missing required field(s) to complete your Vendoo sign up. Please make sure the email, name, and password fields have been filled.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {(action: UIAlertAction!) in
})) }))
@ -101,7 +136,6 @@ extension SignUpViewController {
extension SignUpViewController: UITextFieldDelegate { extension SignUpViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool { func textFieldShouldReturn(textField: UITextField) -> Bool {
//dismissKeyboard()
self.view.endEditing(true) self.view.endEditing(true)
return false return false
} }