From ec88c024e6473212cc3064f182c44c1aebd8fcb6 Mon Sep 17 00:00:00 2001 From: Andrea Mazzini Date: Mon, 15 Aug 2016 10:37:14 +0200 Subject: [PATCH] Improve syntax --- .../ComplicationController.swift | 130 ++++++------ .../ExtensionDelegate.swift | 102 ++++----- .../GlanceController.swift | 26 +-- .../InterfaceController.swift | 126 ++++++------ .../NotificationController.swift | 20 +- .../WatchEntryHelper.swift | 124 +++++------ Gulps/AppDelegate.swift | 194 +++++++++--------- .../Onboarding/GoalViewController.swift | 78 +++---- .../Onboarding/GulpsViewController.swift | 134 ++++++------ .../Onboarding/MeasureViewController.swift | 86 ++++---- .../NotificationViewController.swift | 138 ++++++------- .../Onboarding/OnboardingViewController.swift | 42 ++-- .../TodayViewController+Animation.swift | 40 ++-- 13 files changed, 620 insertions(+), 620 deletions(-) diff --git a/Gulps WatchKit Extension/ComplicationController.swift b/Gulps WatchKit Extension/ComplicationController.swift index 812f7f1..9279a81 100644 --- a/Gulps WatchKit Extension/ComplicationController.swift +++ b/Gulps WatchKit Extension/ComplicationController.swift @@ -3,75 +3,75 @@ import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { - func requestedUpdateDidBegin() { - let server = CLKComplicationServer.sharedInstance() - guard let activeComplications = server.activeComplications else { return } - activeComplications.forEach { server.reloadTimelineForComplication($0) } - } + func requestedUpdateDidBegin() { + let server = CLKComplicationServer.sharedInstance() + guard let activeComplications = server.activeComplications else { return } + activeComplications.forEach { server.reloadTimelineForComplication($0) } + } - func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { - if complication.family == .UtilitarianSmall { - let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat() - smallFlat.textProvider = CLKSimpleTextProvider(text: "42%") - smallFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - smallFlat.tintColor = .mainColor() - handler(smallFlat) - } else if complication.family == .UtilitarianLarge { - let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat() - largeFlat.textProvider = CLKSimpleTextProvider(text: "Goal: 42%", shortText:"42%") - largeFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - largeFlat.tintColor = .mainColor() - handler(largeFlat) - } else if complication.family == .CircularSmall { - let circularSmall = CLKComplicationTemplateCircularSmallRingImage() - circularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - circularSmall.ringStyle = .Closed - circularSmall.tintColor = .mainColor() - handler(circularSmall) - } else if complication.family == .ModularSmall { - let modularSmall = CLKComplicationTemplateModularSmallRingImage() - modularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - modularSmall.ringStyle = .Closed - modularSmall.tintColor = .mainColor() - handler(modularSmall) - } + func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { + if complication.family == .UtilitarianSmall { + let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat() + smallFlat.textProvider = CLKSimpleTextProvider(text: "42%") + smallFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + smallFlat.tintColor = .mainColor() + handler(smallFlat) + } else if complication.family == .UtilitarianLarge { + let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat() + largeFlat.textProvider = CLKSimpleTextProvider(text: "Goal: 42%", shortText:"42%") + largeFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + largeFlat.tintColor = .mainColor() + handler(largeFlat) + } else if complication.family == .CircularSmall { + let circularSmall = CLKComplicationTemplateCircularSmallRingImage() + circularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + circularSmall.ringStyle = .Closed + circularSmall.tintColor = .mainColor() + handler(circularSmall) + } else if complication.family == .ModularSmall { + let modularSmall = CLKComplicationTemplateModularSmallRingImage() + modularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + modularSmall.ringStyle = .Closed + modularSmall.tintColor = .mainColor() + handler(modularSmall) } + } - func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) { - let percentage = WatchEntryHelper.sharedHelper.percentage() ?? 0 + func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) { + let percentage = WatchEntryHelper.sharedHelper.percentage() ?? 0 - if complication.family == .UtilitarianSmall { - let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat() - smallFlat.textProvider = CLKSimpleTextProvider(text: "\(percentage)%") - smallFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - smallFlat.tintColor = .mainColor() - handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: smallFlat)) - } else if complication.family == .UtilitarianLarge { - let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat() - largeFlat.textProvider = CLKSimpleTextProvider(text: "Goal: \(percentage)%", shortText: "\(percentage)%") - largeFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - largeFlat.tintColor = .mainColor() - handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: largeFlat)) - } else if complication.family == .CircularSmall { - let circularSmall = CLKComplicationTemplateCircularSmallRingImage() - circularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - circularSmall.ringStyle = .Closed - circularSmall.fillFraction = Float(percentage) / 100.0 - circularSmall.tintColor = .mainColor() - handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: circularSmall)) - } else if complication.family == .ModularSmall { - let modularSmall = CLKComplicationTemplateModularSmallRingImage() - modularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) - modularSmall.ringStyle = .Closed - modularSmall.fillFraction = Float(percentage) / 100.0 - modularSmall.tintColor = .mainColor() - handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: modularSmall)) - } + if complication.family == .UtilitarianSmall { + let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat() + smallFlat.textProvider = CLKSimpleTextProvider(text: "\(percentage)%") + smallFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + smallFlat.tintColor = .mainColor() + handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: smallFlat)) + } else if complication.family == .UtilitarianLarge { + let largeFlat = CLKComplicationTemplateUtilitarianLargeFlat() + largeFlat.textProvider = CLKSimpleTextProvider(text: "Goal: \(percentage)%", shortText: "\(percentage)%") + largeFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + largeFlat.tintColor = .mainColor() + handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: largeFlat)) + } else if complication.family == .CircularSmall { + let circularSmall = CLKComplicationTemplateCircularSmallRingImage() + circularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + circularSmall.ringStyle = .Closed + circularSmall.fillFraction = Float(percentage) / 100.0 + circularSmall.tintColor = .mainColor() + handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: circularSmall)) + } else if complication.family == .ModularSmall { + let modularSmall = CLKComplicationTemplateModularSmallRingImage() + modularSmall.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!) + modularSmall.ringStyle = .Closed + modularSmall.fillFraction = Float(percentage) / 100.0 + modularSmall.tintColor = .mainColor() + handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: modularSmall)) } - - // MARK: - Time Travel + } - func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { - handler(.None) - } + // MARK: - Time Travel + + func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { + handler(.None) + } } diff --git a/Gulps WatchKit Extension/ExtensionDelegate.swift b/Gulps WatchKit Extension/ExtensionDelegate.swift index 5a8e1c4..0d7a6d5 100644 --- a/Gulps WatchKit Extension/ExtensionDelegate.swift +++ b/Gulps WatchKit Extension/ExtensionDelegate.swift @@ -4,69 +4,69 @@ import ClockKit class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate { - lazy var notificationCenter: NSNotificationCenter = { - return NSNotificationCenter.defaultCenter() - }() + lazy var notificationCenter: NSNotificationCenter = { + return NSNotificationCenter.defaultCenter() + }() - func applicationDidFinishLaunching() { - setupWatchConnectivity() - setupNotificationCenter() - } + func applicationDidFinishLaunching() { + setupWatchConnectivity() + setupNotificationCenter() + } - // MARK: - Notification Center + // MARK: - Notification Center - private func setupNotificationCenter() { - notificationCenter.addObserverForName(NotificationWatchGulpAdded, object: nil, queue: nil) { - (notification: NSNotification) in - self.sendApplicationContext() - self.reloadComplications() - } + private func setupNotificationCenter() { + notificationCenter.addObserverForName(NotificationWatchGulpAdded, object: nil, queue: nil) { + (notification: NSNotification) in + self.sendApplicationContext() + self.reloadComplications() } + } - // MARK: - Watch Connectivity - - private func setupWatchConnectivity() { - guard WCSession.isSupported() else { - return - } + // MARK: - Watch Connectivity - let session = WCSession.defaultSession() - session.delegate = self - session.activateSession() + private func setupWatchConnectivity() { + guard WCSession.isSupported() else { + return } - private func sendApplicationContext() { - guard WCSession.isSupported() else { - return - } + let session = WCSession.defaultSession() + session.delegate = self + session.activateSession() + } + + private func sendApplicationContext() { + guard WCSession.isSupported() else { + return + } - do { - let context = WatchEntryHelper.sharedHelper.applicationContext() - try WCSession.defaultSession().updateApplicationContext(context) - } catch { - print("Unable to send cache data to WCSession: \(error)") - } + do { + let context = WatchEntryHelper.sharedHelper.applicationContext() + try WCSession.defaultSession().updateApplicationContext(context) + } catch { + print("Unable to send cache data to WCSession: \(error)") } + } - func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { - if let goal = applicationContext[Constants.Gulp.Goal.key()] as? Double, - let current = applicationContext[Constants.WatchContext.Current.key()] as? Double, - let small = applicationContext[Constants.Gulp.Small.key()] as? Double, - let big = applicationContext[Constants.Gulp.Big.key()] as? Double { - WatchEntryHelper.sharedHelper.saveSettings(goal: goal, current: current, small: small, big: big) - NSNotificationCenter.defaultCenter().postNotificationName(NotificationContextReceived, object: nil) - self.reloadComplications() - } + func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { + if let goal = applicationContext[Constants.Gulp.Goal.key()] as? Double, + let current = applicationContext[Constants.WatchContext.Current.key()] as? Double, + let small = applicationContext[Constants.Gulp.Small.key()] as? Double, + let big = applicationContext[Constants.Gulp.Big.key()] as? Double { + WatchEntryHelper.sharedHelper.saveSettings(goal: goal, current: current, small: small, big: big) + NSNotificationCenter.defaultCenter().postNotificationName(NotificationContextReceived, object: nil) + self.reloadComplications() } + } - func reloadComplications() { - dispatch_async(dispatch_get_main_queue()) { - if let complications: [CLKComplication] = CLKComplicationServer.sharedInstance().activeComplications { - complications.forEach({ - (complication: CLKComplication) in - CLKComplicationServer.sharedInstance().reloadTimelineForComplication(complication) - }) - } - } + func reloadComplications() { + dispatch_async(dispatch_get_main_queue()) { + if let complications: [CLKComplication] = CLKComplicationServer.sharedInstance().activeComplications { + complications.forEach({ + (complication: CLKComplication) in + CLKComplicationServer.sharedInstance().reloadTimelineForComplication(complication) + }) + } } + } } diff --git a/Gulps WatchKit Extension/GlanceController.swift b/Gulps WatchKit Extension/GlanceController.swift index 702b762..096d872 100644 --- a/Gulps WatchKit Extension/GlanceController.swift +++ b/Gulps WatchKit Extension/GlanceController.swift @@ -3,21 +3,21 @@ import Foundation class GlanceController: WKInterfaceController { - @IBOutlet weak var percentageLabel: WKInterfaceLabel! - - override func awakeWithContext(context: AnyObject?) { - super.awakeWithContext(context) - } + @IBOutlet weak var percentageLabel: WKInterfaceLabel! - override func willActivate() { - super.willActivate() - if let percentage = WatchEntryHelper.sharedHelper.percentage() { - percentageLabel.setText("\(percentage)%") - } - } + override func awakeWithContext(context: AnyObject?) { + super.awakeWithContext(context) + } - override func didDeactivate() { - super.didDeactivate() + override func willActivate() { + super.willActivate() + if let percentage = WatchEntryHelper.sharedHelper.percentage() { + percentageLabel.setText("\(percentage)%") } + } + + override func didDeactivate() { + super.didDeactivate() + } } diff --git a/Gulps WatchKit Extension/InterfaceController.swift b/Gulps WatchKit Extension/InterfaceController.swift index b816822..13e40c7 100644 --- a/Gulps WatchKit Extension/InterfaceController.swift +++ b/Gulps WatchKit Extension/InterfaceController.swift @@ -7,51 +7,51 @@ let NotificationWatchGulpAdded = "NotificationWatchGulpAdded" class InterfaceController: WKInterfaceController, WCSessionDelegate { - @IBOutlet weak var goalLabel: WKInterfaceLabel! - @IBOutlet weak var progressImage: WKInterfaceImage! - lazy var notificationCenter: NSNotificationCenter = { - return NSNotificationCenter.defaultCenter() - }() - var previousPercentage = 0.0 - - override func awakeWithContext(context: AnyObject?) { - super.awakeWithContext(context) - setupNotificationCenter() - - progressImage.setImageNamed("activity-") - } + @IBOutlet weak var goalLabel: WKInterfaceLabel! + @IBOutlet weak var progressImage: WKInterfaceImage! + lazy var notificationCenter: NSNotificationCenter = { + return NSNotificationCenter.defaultCenter() + }() + var previousPercentage = 0.0 - override func handleActionWithIdentifier(identifier: String?, forLocalNotification localNotification: UILocalNotification) { - reloadAndUpdateUI() - } + override func awakeWithContext(context: AnyObject?) { + super.awakeWithContext(context) + setupNotificationCenter() - override func willActivate() { - super.willActivate() - reloadAndUpdateUI() - } + progressImage.setImageNamed("activity-") + } - override func didDeactivate() { - super.didDeactivate() - notificationCenter.removeObserver(self) - } + override func handleActionWithIdentifier(identifier: String?, forLocalNotification localNotification: UILocalNotification) { + reloadAndUpdateUI() + } - //MARK: - Actions + override func willActivate() { + super.willActivate() + reloadAndUpdateUI() + } - @IBAction func addSmallGulpAction() { - updateWithGulp(Constants.Gulp.Small.key()) - } + override func didDeactivate() { + super.didDeactivate() + notificationCenter.removeObserver(self) + } - @IBAction func addBigGulpAction() { - updateWithGulp(Constants.Gulp.Big.key()) - } + //MARK: - Actions + + @IBAction func addSmallGulpAction() { + updateWithGulp(Constants.Gulp.Small.key()) + } + + @IBAction func addBigGulpAction() { + updateWithGulp(Constants.Gulp.Big.key()) + } - // MARK: - Notification Center + // MARK: - Notification Center - private func setupNotificationCenter() { - notificationCenter.addObserverForName(NotificationContextReceived, object: nil, queue: nil) { _ in - self.reloadAndUpdateUI() - } + private func setupNotificationCenter() { + notificationCenter.addObserverForName(NotificationContextReceived, object: nil, queue: nil) { _ in + self.reloadAndUpdateUI() } + } } // MARK: - Private Helper Methods @@ -59,35 +59,35 @@ class InterfaceController: WKInterfaceController, WCSessionDelegate { typealias InterfaceHelper = InterfaceController private extension InterfaceHelper { - func reloadAndUpdateUI() { - if NSUserDefaults.standardUserDefaults().doubleForKey(Constants.Gulp.Goal.key()) == 0 { - progressImage.setHidden(true) - goalLabel.setText(NSLocalizedString("watch.please_onboard", comment: "Shown when the user did not start the iPhone app yet")) - return - } - - progressImage.setHidden(false) - - let percentage = WatchEntryHelper.sharedHelper.percentage() ?? 0 - var delta = (percentage > 100 ? 100 : percentage) - Int(previousPercentage) - if (delta < 0) { - // animate in reverse using negative duration - progressImage.startAnimatingWithImagesInRange(NSMakeRange(percentage, -delta), duration: -1.0, repeatCount: 1) - } else { - if (delta == 0) { - // if the range's length is 0, no image is loaded - delta = 1 - } - progressImage.startAnimatingWithImagesInRange(NSMakeRange(Int(previousPercentage), delta), duration: 1.0, repeatCount: 1) - } - goalLabel.setText("\(NSLocalizedString("daily goal:", comment: "")) \(percentage)%") - previousPercentage = Double(percentage) + func reloadAndUpdateUI() { + if NSUserDefaults.standardUserDefaults().doubleForKey(Constants.Gulp.Goal.key()) == 0 { + progressImage.setHidden(true) + goalLabel.setText(NSLocalizedString("watch.please_onboard", comment: "Shown when the user did not start the iPhone app yet")) + return } - func updateWithGulp(gulp: String) { - WatchEntryHelper.sharedHelper.addGulp(gulp) - reloadAndUpdateUI() - NSNotificationCenter.defaultCenter().postNotificationName(NotificationWatchGulpAdded, object: gulp) + progressImage.setHidden(false) + + let percentage = WatchEntryHelper.sharedHelper.percentage() ?? 0 + var delta = (percentage > 100 ? 100 : percentage) - Int(previousPercentage) + if (delta < 0) { + // animate in reverse using negative duration + progressImage.startAnimatingWithImagesInRange(NSMakeRange(percentage, -delta), duration: -1.0, repeatCount: 1) + } else { + if (delta == 0) { + // if the range's length is 0, no image is loaded + delta = 1 + } + progressImage.startAnimatingWithImagesInRange(NSMakeRange(Int(previousPercentage), delta), duration: 1.0, repeatCount: 1) } + goalLabel.setText("\(NSLocalizedString("daily goal:", comment: "")) \(percentage)%") + previousPercentage = Double(percentage) + } + + func updateWithGulp(gulp: String) { + WatchEntryHelper.sharedHelper.addGulp(gulp) + reloadAndUpdateUI() + NSNotificationCenter.defaultCenter().postNotificationName(NotificationWatchGulpAdded, object: gulp) + } } diff --git a/Gulps WatchKit Extension/NotificationController.swift b/Gulps WatchKit Extension/NotificationController.swift index 5f7b209..3e3b025 100644 --- a/Gulps WatchKit Extension/NotificationController.swift +++ b/Gulps WatchKit Extension/NotificationController.swift @@ -3,16 +3,16 @@ import Foundation class NotificationController: WKUserNotificationInterfaceController { - override init() { - super.init() - self.setTitle("Gulps") - } + override init() { + super.init() + self.setTitle("Gulps") + } - override func willActivate() { - super.willActivate() - } + override func willActivate() { + super.willActivate() + } - override func didDeactivate() { - super.didDeactivate() - } + override func didDeactivate() { + super.didDeactivate() + } } diff --git a/Gulps WatchKit Extension/WatchEntryHelper.swift b/Gulps WatchKit Extension/WatchEntryHelper.swift index 855ab1f..ce47360 100644 --- a/Gulps WatchKit Extension/WatchEntryHelper.swift +++ b/Gulps WatchKit Extension/WatchEntryHelper.swift @@ -1,73 +1,73 @@ import Foundation class WatchEntryHelper { - static let sharedHelper = WatchEntryHelper() - lazy var userDefaults = NSUserDefaults.standardUserDefaults() + static let sharedHelper = WatchEntryHelper() + lazy var userDefaults = NSUserDefaults.standardUserDefaults() - /** - Save settings received by - - parameter goal: The daily goal - - parameter current: The current progress - - parameter small: The small portion size - - parameter big: The big portion size - */ - func saveSettings(goal goal: Double, current: Double, small: Double, big: Double) { - userDefaults.setDouble(goal, forKey: Constants.Gulp.Goal.key()) - userDefaults.setDouble(small, forKey: Constants.Gulp.Small.key()) - userDefaults.setDouble(big, forKey: Constants.Gulp.Big.key()) - userDefaults.setObject(NSDate(), forKey: Constants.WatchContext.Date.key()) - userDefaults.setDouble(current, forKey: Constants.WatchContext.Current.key()) - userDefaults.synchronize() - } - - /** - Save settings received by - - parameter portion: The portion key - */ - func addGulp(portion: String) { - let portion = userDefaults.doubleForKey(portion) - userDefaults.setDouble(quantity() + portion, forKey: Constants.WatchContext.Current.key()) - userDefaults.setObject(NSDate(), forKey: Constants.WatchContext.Date.key()) - userDefaults.synchronize() - } + /** + Save settings received by + - parameter goal: The daily goal + - parameter current: The current progress + - parameter small: The small portion size + - parameter big: The big portion size + */ + func saveSettings(goal goal: Double, current: Double, small: Double, big: Double) { + userDefaults.setDouble(goal, forKey: Constants.Gulp.Goal.key()) + userDefaults.setDouble(small, forKey: Constants.Gulp.Small.key()) + userDefaults.setDouble(big, forKey: Constants.Gulp.Big.key()) + userDefaults.setObject(NSDate(), forKey: Constants.WatchContext.Date.key()) + userDefaults.setDouble(current, forKey: Constants.WatchContext.Current.key()) + userDefaults.synchronize() + } - /** - Application Context sent by the watch - - Returns: [String: Double] - */ - func applicationContext() -> [String: Double] { - return [ - Constants.Gulp.Goal.key(): userDefaults.doubleForKey(Constants.Gulp.Goal.key()), - Constants.WatchContext.Current.key(): quantity(), - Constants.Gulp.Small.key(): userDefaults.doubleForKey(Constants.Gulp.Small.key()), - Constants.Gulp.Big.key(): userDefaults.doubleForKey(Constants.Gulp.Big.key())] - } + /** + Save settings received by + - parameter portion: The portion key + */ + func addGulp(portion: String) { + let portion = userDefaults.doubleForKey(portion) + userDefaults.setDouble(quantity() + portion, forKey: Constants.WatchContext.Current.key()) + userDefaults.setObject(NSDate(), forKey: Constants.WatchContext.Date.key()) + userDefaults.synchronize() + } - /** - Returns the current quantity - It also checks if the data is stale, resetting the quantity if needed - - Returns: Double the current quantity - */ - func quantity() -> Double { - let quantity = userDefaults.doubleForKey(Constants.WatchContext.Current.key()) + /** + Application Context sent by the watch + - Returns: [String: Double] + */ + func applicationContext() -> [String: Double] { + return [ + Constants.Gulp.Goal.key(): userDefaults.doubleForKey(Constants.Gulp.Goal.key()), + Constants.WatchContext.Current.key(): quantity(), + Constants.Gulp.Small.key(): userDefaults.doubleForKey(Constants.Gulp.Small.key()), + Constants.Gulp.Big.key(): userDefaults.doubleForKey(Constants.Gulp.Big.key())] + } - if let date = userDefaults.objectForKey(Constants.WatchContext.Date.key()) as? NSDate { - if let tomorrow = date.startOfTomorrow where NSDate().compare(tomorrow) != NSComparisonResult.OrderedAscending { - // Data is stale, reset the counter - return 0 - } - } + /** + Returns the current quantity + It also checks if the data is stale, resetting the quantity if needed + - Returns: Double the current quantity + */ + func quantity() -> Double { + let quantity = userDefaults.doubleForKey(Constants.WatchContext.Current.key()) - return quantity + if let date = userDefaults.objectForKey(Constants.WatchContext.Date.key()) as? NSDate { + if let tomorrow = date.startOfTomorrow where NSDate().compare(tomorrow) != NSComparisonResult.OrderedAscending { + // Data is stale, reset the counter + return 0 + } } - /** - Returns the current percentage, if available - The data might not be there yet (app just installed) - - Returns: Int? the current percentage - */ - func percentage() -> Int? { - let goal = userDefaults.doubleForKey(Constants.Gulp.Goal.key()) - return Int(round(quantity() / goal * 100.0)) - } + return quantity + } + + /** + Returns the current percentage, if available + The data might not be there yet (app just installed) + - Returns: Int? the current percentage + */ + func percentage() -> Int? { + let goal = userDefaults.doubleForKey(Constants.Gulp.Goal.key()) + return Int(round(quantity() / goal * 100.0)) + } } diff --git a/Gulps/AppDelegate.swift b/Gulps/AppDelegate.swift index 0aef76c..0f97317 100644 --- a/Gulps/AppDelegate.swift +++ b/Gulps/AppDelegate.swift @@ -5,121 +5,121 @@ import Realm @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { - var window: UIWindow? - var realmNotification: RLMNotificationToken? - let watchConnectivityHelper = WatchConnectivityHelper() - - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { - - setupAppearance() - Settings.registerDefaults() - watchConnectivityHelper.setupWatchConnectivity(delegate: self) - - let userDefaults = NSUserDefaults.groupUserDefaults() - if (!userDefaults.boolForKey(Constants.General.OnboardingShown.key())) { - loadOnboardingInterface() - } else { - loadMainInterface() - checkVersion() - } - - return true + var window: UIWindow? + var realmNotification: RLMNotificationToken? + let watchConnectivityHelper = WatchConnectivityHelper() + + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + + setupAppearance() + Settings.registerDefaults() + watchConnectivityHelper.setupWatchConnectivity(delegate: self) + + let userDefaults = NSUserDefaults.groupUserDefaults() + if (!userDefaults.boolForKey(Constants.General.OnboardingShown.key())) { + loadOnboardingInterface() + } else { + loadMainInterface() + checkVersion() } - /** - Check the app version and perform required tasks when upgrading - */ - func checkVersion() { - let userDefaults = NSUserDefaults.groupUserDefaults() - let current = userDefaults.integerForKey("BUNDLE_VERSION") - if let versionString = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String, let version = Int(versionString) { - if current < 13 { - NotificationHelper.rescheduleNotifications() - } - userDefaults.setInteger(version, forKey: "BUNDLE_VERSION") - userDefaults.synchronize() - } + return true + } + + /** + Check the app version and perform required tasks when upgrading + */ + func checkVersion() { + let userDefaults = NSUserDefaults.groupUserDefaults() + let current = userDefaults.integerForKey("BUNDLE_VERSION") + if let versionString = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String, let version = Int(versionString) { + if current < 13 { + NotificationHelper.rescheduleNotifications() + } + userDefaults.setInteger(version, forKey: "BUNDLE_VERSION") + userDefaults.synchronize() } + } - /** - Sets the main appearance of the app - */ - func setupAppearance() { - Globals.actionSheetAppearance() - - UIApplication.sharedApplication().statusBarStyle = .LightContent + /** + Sets the main appearance of the app + */ + func setupAppearance() { + Globals.actionSheetAppearance() - UITabBar.appearance().tintColor = .mainColor() + UIApplication.sharedApplication().statusBarStyle = .LightContent - if let font = UIFont(name: "KaushanScript-Regular", size: 22) { - UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()] - } - - UINavigationBar.appearance().barTintColor = .mainColor() - UINavigationBar.appearance().tintColor = .whiteColor() + UITabBar.appearance().tintColor = .mainColor() - window?.backgroundColor = .whiteColor() + if let font = UIFont(name: "KaushanScript-Regular", size: 22) { + UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()] } - /** - Present the onboarding controller if needed - */ - func loadOnboardingInterface() { - let storyboard = UIStoryboard(name: "Onboarding", bundle: nil) - if let controller = storyboard.instantiateInitialViewController() { - self.window?.rootViewController = controller - } - } + UINavigationBar.appearance().barTintColor = .mainColor() + UINavigationBar.appearance().tintColor = .whiteColor() - /** - Present the main interface - */ - func loadMainInterface() { - realmNotification = watchConnectivityHelper.setupWatchUpdates() - let storyboard = UIStoryboard(name: "Main", bundle: nil) - if let controller = storyboard.instantiateInitialViewController() { - self.window?.rootViewController = controller - } - } - - // MARK: - Notification handler + window?.backgroundColor = .whiteColor() + } - func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { - if let identifier = identifier { - NotificationHelper.handleNotification(notification, identifier: identifier) - } - completionHandler() + /** + Present the onboarding controller if needed + */ + func loadOnboardingInterface() { + let storyboard = UIStoryboard(name: "Onboarding", bundle: nil) + if let controller = storyboard.instantiateInitialViewController() { + self.window?.rootViewController = controller } - - func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { - if (UIApplication.sharedApplication().scheduledLocalNotifications?.count == 0) { - NotificationHelper.registerNotifications() - } + } + + /** + Present the main interface + */ + func loadMainInterface() { + realmNotification = watchConnectivityHelper.setupWatchUpdates() + let storyboard = UIStoryboard(name: "Main", bundle: nil) + if let controller = storyboard.instantiateInitialViewController() { + self.window?.rootViewController = controller } + } - // MARK: - 3D Touch shortcut + // MARK: - Notification handler - enum ShortcutType: String { - case Big = "it.fancypixel.gulps.big" - case Small = "it.fancypixel.gulps.small" + func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { + if let identifier = identifier { + NotificationHelper.handleNotification(notification, identifier: identifier) } + completionHandler() + } - func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { - handleShortcutItem(shortcutItem) - completionHandler(true) + func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { + if (UIApplication.sharedApplication().scheduledLocalNotifications?.count == 0) { + NotificationHelper.registerNotifications() } - - func handleShortcutItem(item: UIApplicationShortcutItem) { - if let type = ShortcutType(rawValue: item.type) { - if (type == .Small) { - EntryHandler.sharedHandler.addGulp(NSUserDefaults.groupUserDefaults().doubleForKey(Constants.Gulp.Small.key())) - } else if (type == .Big) { - EntryHandler.sharedHandler.addGulp(NSUserDefaults.groupUserDefaults().doubleForKey(Constants.Gulp.Big.key())) - } - } + } + + // MARK: - 3D Touch shortcut + + enum ShortcutType: String { + case Big = "it.fancypixel.gulps.big" + case Small = "it.fancypixel.gulps.small" + } + + func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { + handleShortcutItem(shortcutItem) + completionHandler(true) + } + + func handleShortcutItem(item: UIApplicationShortcutItem) { + if let type = ShortcutType(rawValue: item.type) { + if (type == .Small) { + EntryHandler.sharedHandler.addGulp(NSUserDefaults.groupUserDefaults().doubleForKey(Constants.Gulp.Small.key())) + } else if (type == .Big) { + EntryHandler.sharedHandler.addGulp(NSUserDefaults.groupUserDefaults().doubleForKey(Constants.Gulp.Big.key())) + } } + } - func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { - watchConnectivityHelper.session(session, didReceiveApplicationContext: applicationContext) - } + func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { + watchConnectivityHelper.session(session, didReceiveApplicationContext: applicationContext) + } } diff --git a/Gulps/ViewControllers/Onboarding/GoalViewController.swift b/Gulps/ViewControllers/Onboarding/GoalViewController.swift index cee0a32..505e6be 100644 --- a/Gulps/ViewControllers/Onboarding/GoalViewController.swift +++ b/Gulps/ViewControllers/Onboarding/GoalViewController.swift @@ -2,54 +2,54 @@ import UIKit class GoalViewController: OnboardingViewController, UITextFieldDelegate { - @IBOutlet weak var goalTextField: UITextField! - @IBOutlet weak var goalSuffixLabel: UILabel! - @IBOutlet weak var headerLabel: UILabel! - @IBOutlet weak var goalBackgroundView: UIView! - let userDefaults = NSUserDefaults.groupUserDefaults() - - override func viewDidLoad() { - super.viewDidLoad() - - self.goalTextField.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GoalViewController.dismissAndSave)) - self.goalBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.goalTextField, action: #selector(UIResponder.becomeFirstResponder))) + @IBOutlet weak var goalTextField: UITextField! + @IBOutlet weak var goalSuffixLabel: UILabel! + @IBOutlet weak var headerLabel: UILabel! + @IBOutlet weak var goalBackgroundView: UIView! + let userDefaults = NSUserDefaults.groupUserDefaults() + + override func viewDidLoad() { + super.viewDidLoad() + + self.goalTextField.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GoalViewController.dismissAndSave)) + self.goalBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.goalTextField, action: #selector(UIResponder.becomeFirstResponder))) + } + + func dismissAndSave() { + guard let text = goalTextField.text else { + return } - func dismissAndSave() { - guard let text = goalTextField.text else { - return - } - - let numberFormatter = NSNumberFormatter() - numberFormatter.numberStyle = .DecimalStyle + let numberFormatter = NSNumberFormatter() + numberFormatter.numberStyle = .DecimalStyle - self.goalTextField.resignFirstResponder() + self.goalTextField.resignFirstResponder() - var goal = 0.0 - if let number = numberFormatter.numberFromString(text) { - goal = number as Double - } - - self.userDefaults.setDouble(goal, forKey: Constants.Gulp.Goal.key()) - self.userDefaults.synchronize() + var goal = 0.0 + if let number = numberFormatter.numberFromString(text) { + goal = number as Double } - func textFieldShouldReturn(textField: UITextField) -> Bool { - textField.resignFirstResponder() + self.userDefaults.setDouble(goal, forKey: Constants.Gulp.Goal.key()) + self.userDefaults.synchronize() + } - dismissAndSave() + func textFieldShouldReturn(textField: UITextField) -> Bool { + textField.resignFirstResponder() - return true - } + dismissAndSave() + + return true + } - override func updateUI() { - let numberFormatter = NSNumberFormatter() - numberFormatter.numberStyle = .DecimalStyle - self.goalTextField.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Goal.key())) - let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) + override func updateUI() { + let numberFormatter = NSNumberFormatter() + numberFormatter.numberStyle = .DecimalStyle + self.goalTextField.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Goal.key())) + let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) - if let unit = unit { - self.goalSuffixLabel.text = unit.suffixForUnitOfMeasure() - } + if let unit = unit { + self.goalSuffixLabel.text = unit.suffixForUnitOfMeasure() } + } } diff --git a/Gulps/ViewControllers/Onboarding/GulpsViewController.swift b/Gulps/ViewControllers/Onboarding/GulpsViewController.swift index 3bf32b1..6ef5375 100644 --- a/Gulps/ViewControllers/Onboarding/GulpsViewController.swift +++ b/Gulps/ViewControllers/Onboarding/GulpsViewController.swift @@ -3,88 +3,88 @@ import pop class GulpsViewController: OnboardingViewController, UITextFieldDelegate { - @IBOutlet weak var smallGulpText: UITextField! - @IBOutlet weak var bigGulpText: UITextField! - @IBOutlet weak var smallSuffixLabel: UILabel! - @IBOutlet weak var bigSuffixLabel: UILabel! - @IBOutlet weak var headerLabel: UILabel! - @IBOutlet weak var smallBackgroundView: UIView! - @IBOutlet weak var bigBackgroundView: UIView! + @IBOutlet weak var smallGulpText: UITextField! + @IBOutlet weak var bigGulpText: UITextField! + @IBOutlet weak var smallSuffixLabel: UILabel! + @IBOutlet weak var bigSuffixLabel: UILabel! + @IBOutlet weak var headerLabel: UILabel! + @IBOutlet weak var smallBackgroundView: UIView! + @IBOutlet weak var bigBackgroundView: UIView! - let userDefaults = NSUserDefaults.groupUserDefaults() + let userDefaults = NSUserDefaults.groupUserDefaults() - override func viewDidLoad() { - super.viewDidLoad() + override func viewDidLoad() { + super.viewDidLoad() - self.smallGulpText.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GulpsViewController.dismissAndSave)) - self.bigGulpText.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GulpsViewController.dismissAndSave)) + self.smallGulpText.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GulpsViewController.dismissAndSave)) + self.bigGulpText.inputAccessoryView = Globals.numericToolbar(self, selector: #selector(GulpsViewController.dismissAndSave)) - self.smallBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.smallGulpText, action: #selector(UIResponder.becomeFirstResponder))) - self.bigBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.bigGulpText, action: #selector(UIResponder.becomeFirstResponder))) + self.smallBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.smallGulpText, action: #selector(UIResponder.becomeFirstResponder))) + self.bigBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self.bigGulpText, action: #selector(UIResponder.becomeFirstResponder))) - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GulpsViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GulpsViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) - } - - func dismissAndSave() { - let numberFormatter = NSNumberFormatter() - numberFormatter.numberStyle = .DecimalStyle - - _ = [self.smallGulpText, self.bigGulpText].map({$0.resignFirstResponder()}) + NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GulpsViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) + NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GulpsViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) + } - var small = 0.0 - var big = 0.0 - if let number = numberFormatter.numberFromString(self.smallGulpText.text ?? "0") { - small = number as Double - } + func dismissAndSave() { + let numberFormatter = NSNumberFormatter() + numberFormatter.numberStyle = .DecimalStyle - if let number = numberFormatter.numberFromString(self.bigGulpText.text ?? "0") { - big = number as Double - } + _ = [self.smallGulpText, self.bigGulpText].map({$0.resignFirstResponder()}) - self.userDefaults.setDouble(small, forKey: Constants.Gulp.Small.key()) - self.userDefaults.setDouble(big, forKey: Constants.Gulp.Big.key()) - self.userDefaults.synchronize() + var small = 0.0 + var big = 0.0 + if let number = numberFormatter.numberFromString(self.smallGulpText.text ?? "0") { + small = number as Double } - func textFieldShouldReturn(textField: UITextField) -> Bool { - textField.resignFirstResponder() - - dismissAndSave() - - return true + if let number = numberFormatter.numberFromString(self.bigGulpText.text ?? "0") { + big = number as Double } - override func updateUI() { - let numberFormatter = NSNumberFormatter() - numberFormatter.numberStyle = .DecimalStyle - self.smallGulpText.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Small.key())) - self.bigGulpText.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Big.key())) - let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) - - if let unit = unit { - self.smallSuffixLabel.text = unit.suffixForUnitOfMeasure() - self.bigSuffixLabel.text = unit.suffixForUnitOfMeasure() - } - } + self.userDefaults.setDouble(small, forKey: Constants.Gulp.Small.key()) + self.userDefaults.setDouble(big, forKey: Constants.Gulp.Big.key()) + self.userDefaults.synchronize() + } - override func touchesEnded(touches: Set, withEvent event: UIEvent?) { - _ = [self.smallGulpText, self.bigGulpText].map({$0.resignFirstResponder()}) - } + func textFieldShouldReturn(textField: UITextField) -> Bool { + textField.resignFirstResponder() - func keyboardWillShow(notification: NSNotification) { - scrollViewTo(-(self.headerLabel.frame.origin.y + self.headerLabel.frame.size.height), from: 0) - } + dismissAndSave() - func keyboardWillHide(notification: NSNotification) { - scrollViewTo(0, from: -(self.headerLabel.frame.origin.y + self.headerLabel.frame.size.height)) - } + return true + } + + override func updateUI() { + let numberFormatter = NSNumberFormatter() + numberFormatter.numberStyle = .DecimalStyle + self.smallGulpText.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Small.key())) + self.bigGulpText.text = numberFormatter.stringFromNumber(self.userDefaults.doubleForKey(Constants.Gulp.Big.key())) + let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) - func scrollViewTo(offset: CGFloat, from: CGFloat) { - let move = POPBasicAnimation(propertyNamed: kPOPLayerTranslationY) - move.fromValue = from - move.toValue = offset - move.removedOnCompletion = true - self.view.layer.pop_addAnimation(move, forKey: "move") + if let unit = unit { + self.smallSuffixLabel.text = unit.suffixForUnitOfMeasure() + self.bigSuffixLabel.text = unit.suffixForUnitOfMeasure() } + } + + override func touchesEnded(touches: Set, withEvent event: UIEvent?) { + _ = [self.smallGulpText, self.bigGulpText].map({$0.resignFirstResponder()}) + } + + func keyboardWillShow(notification: NSNotification) { + scrollViewTo(-(self.headerLabel.frame.origin.y + self.headerLabel.frame.size.height), from: 0) + } + + func keyboardWillHide(notification: NSNotification) { + scrollViewTo(0, from: -(self.headerLabel.frame.origin.y + self.headerLabel.frame.size.height)) + } + + func scrollViewTo(offset: CGFloat, from: CGFloat) { + let move = POPBasicAnimation(propertyNamed: kPOPLayerTranslationY) + move.fromValue = from + move.toValue = offset + move.removedOnCompletion = true + self.view.layer.pop_addAnimation(move, forKey: "move") + } } diff --git a/Gulps/ViewControllers/Onboarding/MeasureViewController.swift b/Gulps/ViewControllers/Onboarding/MeasureViewController.swift index b54e548..5d9b550 100644 --- a/Gulps/ViewControllers/Onboarding/MeasureViewController.swift +++ b/Gulps/ViewControllers/Onboarding/MeasureViewController.swift @@ -3,48 +3,48 @@ import pop class MeasureViewController: OnboardingViewController { - @IBOutlet weak var litersCheck: UIImageView! - @IBOutlet weak var ouncesCheck: UIImageView! - let userDefaults = NSUserDefaults.groupUserDefaults() - - override func viewDidLoad() { - super.viewDidLoad() - _ = [litersCheck, ouncesCheck].map({$0.transform = CGAffineTransformMakeScale(0.001, 0.001)}) - } - - override func updateUI() { - let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) - - let scaleUp = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) - scaleUp.fromValue = NSValue(CGPoint: CGPointMake(0, 0)) - scaleUp.toValue = NSValue(CGPoint: CGPointMake(1, 1)) - scaleUp.removedOnCompletion = true - - let scaleDown = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) - scaleDown.fromValue = NSValue(CGPoint: CGPointMake(1, 1)) - scaleDown.toValue = NSValue(CGPoint: CGPointMake(0, 0)) - scaleDown.removedOnCompletion = true - - if (unit == Constants.UnitsOfMeasure.Liters) { - self.litersCheck.pop_addAnimation(scaleUp, forKey: "scaleUp") - self.ouncesCheck.pop_addAnimation(scaleDown, forKey: "scaleDown") - Settings.registerDefaultsForLiter() - } else { - self.litersCheck.pop_addAnimation(scaleDown, forKey: "scaleDown") - self.ouncesCheck.pop_addAnimation(scaleUp, forKey: "scaleUp") - Settings.registerDefaultsForOunces() - } - } - - @IBAction func ouncesButtonAction() { - self.userDefaults.setInteger(Constants.UnitsOfMeasure.Ounces.rawValue, forKey: Constants.General.UnitOfMeasure.key()) - self.userDefaults.synchronize() - updateUI() - } - - @IBAction func litersButtonAction() { - self.userDefaults.setInteger(Constants.UnitsOfMeasure.Liters.rawValue, forKey: Constants.General.UnitOfMeasure.key()) - self.userDefaults.synchronize() - updateUI() + @IBOutlet weak var litersCheck: UIImageView! + @IBOutlet weak var ouncesCheck: UIImageView! + let userDefaults = NSUserDefaults.groupUserDefaults() + + override func viewDidLoad() { + super.viewDidLoad() + [litersCheck, ouncesCheck].forEach {$0.transform = CGAffineTransformMakeScale(0.001, 0.001)} + } + + override func updateUI() { + let unit = Constants.UnitsOfMeasure(rawValue: self.userDefaults.integerForKey(Constants.General.UnitOfMeasure.key())) + + let scaleUp = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) + scaleUp.fromValue = NSValue(CGPoint: CGPointMake(0, 0)) + scaleUp.toValue = NSValue(CGPoint: CGPointMake(1, 1)) + scaleUp.removedOnCompletion = true + + let scaleDown = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) + scaleDown.fromValue = NSValue(CGPoint: CGPointMake(1, 1)) + scaleDown.toValue = NSValue(CGPoint: CGPointMake(0, 0)) + scaleDown.removedOnCompletion = true + + if (unit == Constants.UnitsOfMeasure.Liters) { + self.litersCheck.pop_addAnimation(scaleUp, forKey: "scaleUp") + self.ouncesCheck.pop_addAnimation(scaleDown, forKey: "scaleDown") + Settings.registerDefaultsForLiter() + } else { + self.litersCheck.pop_addAnimation(scaleDown, forKey: "scaleDown") + self.ouncesCheck.pop_addAnimation(scaleUp, forKey: "scaleUp") + Settings.registerDefaultsForOunces() } + } + + @IBAction func ouncesButtonAction() { + self.userDefaults.setInteger(Constants.UnitsOfMeasure.Ounces.rawValue, forKey: Constants.General.UnitOfMeasure.key()) + self.userDefaults.synchronize() + updateUI() + } + + @IBAction func litersButtonAction() { + self.userDefaults.setInteger(Constants.UnitsOfMeasure.Liters.rawValue, forKey: Constants.General.UnitOfMeasure.key()) + self.userDefaults.synchronize() + updateUI() + } } diff --git a/Gulps/ViewControllers/Onboarding/NotificationViewController.swift b/Gulps/ViewControllers/Onboarding/NotificationViewController.swift index 1c128f9..90767ae 100644 --- a/Gulps/ViewControllers/Onboarding/NotificationViewController.swift +++ b/Gulps/ViewControllers/Onboarding/NotificationViewController.swift @@ -3,85 +3,85 @@ import AHKActionSheet class NotificationViewController: OnboardingViewController, UIActionSheetDelegate { - @IBOutlet weak var notificationSwitch: UISwitch! - @IBOutlet weak var fromLabel: UILabel! - @IBOutlet weak var intervalLabel: UILabel! - @IBOutlet weak var toLabel: UILabel! - let userDefaults = NSUserDefaults.groupUserDefaults() + @IBOutlet weak var notificationSwitch: UISwitch! + @IBOutlet weak var fromLabel: UILabel! + @IBOutlet weak var intervalLabel: UILabel! + @IBOutlet weak var toLabel: UILabel! + let userDefaults = NSUserDefaults.groupUserDefaults() - lazy var fromActionSheet: AHKActionSheet = { - var actionSheet = AHKActionSheet(title: NSLocalizedString("from:", comment: "")) - for index in 5...22 { - actionSheet.addButtonWithTitle("\(index):00", type: .Default) { _ in - self.userDefaults.setInteger(index, forKey: Constants.Notification.From.key()) - self.userDefaults.synchronize() - self.updateUI() - } - } - return actionSheet - }() - - lazy var intervalActionSheet: AHKActionSheet = { - var actionSheet = AHKActionSheet(title: NSLocalizedString("every:", comment: "")) - for index in 1...8 { - let hour = index > 1 ? NSLocalizedString("hours", comment: "") : NSLocalizedString("hour", comment: "") - actionSheet.addButtonWithTitle("\(index) \(hour)", type: .Default) { _ in - self.userDefaults.setInteger(index, forKey: Constants.Notification.Interval.key()) - self.userDefaults.synchronize() - self.updateUI() - } - } - return actionSheet - }() - - override func viewDidLoad() { - super.viewDidLoad() - } - - override func updateUI() { - self.fromLabel.text = "\(self.userDefaults.integerForKey(Constants.Notification.From.key())):00" - self.toLabel.text = "\(self.userDefaults.integerForKey(Constants.Notification.To.key())):00" - let interval = self.userDefaults.integerForKey(Constants.Notification.Interval.key()) - let hour = interval > 1 ? NSLocalizedString("hours", comment: "") : NSLocalizedString("hour", comment: "") - self.intervalLabel.text = "\(interval) \(hour)" - self.notificationSwitch.on = self.userDefaults.boolForKey(Constants.Notification.On.key()) + lazy var fromActionSheet: AHKActionSheet = { + var actionSheet = AHKActionSheet(title: NSLocalizedString("from:", comment: "")) + for index in 5...22 { + actionSheet.addButtonWithTitle("\(index):00", type: .Default) { _ in + self.userDefaults.setInteger(index, forKey: Constants.Notification.From.key()) + self.userDefaults.synchronize() + self.updateUI() + } } + return actionSheet + }() - @IBAction func openFromSelection(sender: UIButton) { - self.fromActionSheet.show() + lazy var intervalActionSheet: AHKActionSheet = { + var actionSheet = AHKActionSheet(title: NSLocalizedString("every:", comment: "")) + for index in 1...8 { + let hour = index > 1 ? NSLocalizedString("hours", comment: "") : NSLocalizedString("hour", comment: "") + actionSheet.addButtonWithTitle("\(index) \(hour)", type: .Default) { _ in + self.userDefaults.setInteger(index, forKey: Constants.Notification.Interval.key()) + self.userDefaults.synchronize() + self.updateUI() + } } + return actionSheet + }() - @IBAction func openIntervalSelection(sender: UIButton) { - self.intervalActionSheet.show() - } + override func viewDidLoad() { + super.viewDidLoad() + } - @IBAction func openToSelection(sender: UIButton) { - let toActionSheet = AHKActionSheet(title: NSLocalizedString("to:", comment: "")) - let upper = self.userDefaults.integerForKey(Constants.Notification.From.key()) + 1 - for index in upper...24 { - toActionSheet!.addButtonWithTitle("\(index):00", type: .Default) { _ in - self.userDefaults.setInteger(index, forKey: Constants.Notification.To.key()) - self.userDefaults.synchronize() - self.updateUI() - } - } - toActionSheet.show() - } + override func updateUI() { + self.fromLabel.text = "\(self.userDefaults.integerForKey(Constants.Notification.From.key())):00" + self.toLabel.text = "\(self.userDefaults.integerForKey(Constants.Notification.To.key())):00" + let interval = self.userDefaults.integerForKey(Constants.Notification.Interval.key()) + let hour = interval > 1 ? NSLocalizedString("hours", comment: "") : NSLocalizedString("hour", comment: "") + self.intervalLabel.text = "\(interval) \(hour)" + self.notificationSwitch.on = self.userDefaults.boolForKey(Constants.Notification.On.key()) + } + + @IBAction func openFromSelection(sender: UIButton) { + self.fromActionSheet.show() + } + + @IBAction func openIntervalSelection(sender: UIButton) { + self.intervalActionSheet.show() + } - @IBAction func enableNotifications(sender: UISwitch) { - self.userDefaults.setBool(sender.on, forKey: Constants.Notification.On.key()) + @IBAction func openToSelection(sender: UIButton) { + let toActionSheet = AHKActionSheet(title: NSLocalizedString("to:", comment: "")) + let upper = self.userDefaults.integerForKey(Constants.Notification.From.key()) + 1 + for index in upper...24 { + toActionSheet!.addButtonWithTitle("\(index):00", type: .Default) { _ in + self.userDefaults.setInteger(index, forKey: Constants.Notification.To.key()) self.userDefaults.synchronize() + self.updateUI() + } } + toActionSheet.show() + } - @IBAction func doneAction() { - userDefaults.setBool(true, forKey: Constants.General.OnboardingShown.key()) - NotificationHelper.unscheduleNotifications() - if notificationSwitch.on { - NotificationHelper.askPermission() - } + @IBAction func enableNotifications(sender: UISwitch) { + self.userDefaults.setBool(sender.on, forKey: Constants.Notification.On.key()) + self.userDefaults.synchronize() + } + + @IBAction func doneAction() { + userDefaults.setBool(true, forKey: Constants.General.OnboardingShown.key()) + NotificationHelper.unscheduleNotifications() + if notificationSwitch.on { + NotificationHelper.askPermission() + } - if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { - appDelegate.loadMainInterface() - } + if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { + appDelegate.loadMainInterface() } + } } diff --git a/Gulps/ViewControllers/Onboarding/OnboardingViewController.swift b/Gulps/ViewControllers/Onboarding/OnboardingViewController.swift index bc89174..7ab855c 100644 --- a/Gulps/ViewControllers/Onboarding/OnboardingViewController.swift +++ b/Gulps/ViewControllers/Onboarding/OnboardingViewController.swift @@ -3,34 +3,34 @@ import AMWaveTransition class OnboardingViewController: AMWaveViewController { - @IBOutlet var viewArray: [UIView]! + @IBOutlet var viewArray: [UIView]! - override func viewDidLoad() { - super.viewDidLoad() + override func viewDidLoad() { + super.viewDidLoad() - self.navigationController?.view.backgroundColor = UIColor.mainColor() - self.view.backgroundColor = UIColor.clearColor() + self.navigationController?.view.backgroundColor = UIColor.mainColor() + self.view.backgroundColor = UIColor.clearColor() - updateUI() - } + updateUI() + } - override func prefersStatusBarHidden() -> Bool { - return true - } + override func prefersStatusBarHidden() -> Bool { + return true + } - override func visibleCells() -> [AnyObject]! { - return self.viewArray - } + override func visibleCells() -> [AnyObject]! { + return self.viewArray + } - func updateUI() { + func updateUI() { - } + } - @IBAction func backAction() { - self.navigationController?.popViewControllerAnimated(true) - } + @IBAction func backAction() { + self.navigationController?.popViewControllerAnimated(true) + } - func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { - return Globals.numericTextField(textField, shouldChangeCharactersInRange: range, replacementString: string) - } + func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { + return Globals.numericTextField(textField, shouldChangeCharactersInRange: range, replacementString: string) + } } diff --git a/GulpsToday/TodayViewController+Animation.swift b/GulpsToday/TodayViewController+Animation.swift index 34fcb3a..831aedb 100644 --- a/GulpsToday/TodayViewController+Animation.swift +++ b/GulpsToday/TodayViewController+Animation.swift @@ -1,27 +1,27 @@ import UIKit extension TodayViewController { - func showConfirmButtons() { - UIView.animateWithDuration(0.2, animations: { () -> Void in - self.bigGulpButton.transform = CGAffineTransformMakeScale(0.001, 0.001) - self.smallGulpButton.transform = CGAffineTransformMakeScale(0.001, 0.001) - }) { (_) -> Void in - UIView.animateWithDuration(0.2) { - self.bigConfirmButton.transform = CGAffineTransformMakeScale(1, 1) - self.smallConfirmButton.transform = CGAffineTransformMakeScale(1, 1) - }; - } + func showConfirmButtons() { + UIView.animateWithDuration(0.2, animations: { () -> Void in + self.bigGulpButton.transform = CGAffineTransformMakeScale(0.001, 0.001) + self.smallGulpButton.transform = CGAffineTransformMakeScale(0.001, 0.001) + }) { (_) -> Void in + UIView.animateWithDuration(0.2) { + self.bigConfirmButton.transform = CGAffineTransformMakeScale(1, 1) + self.smallConfirmButton.transform = CGAffineTransformMakeScale(1, 1) + }; } + } - func hideConfirmButtons() { - UIView.animateWithDuration(0.2, animations: { () -> Void in - self.bigConfirmButton.transform = CGAffineTransformMakeScale(0.001, 0.001) - self.smallConfirmButton.transform = CGAffineTransformMakeScale(0.001, 0.001) - }) { (_) -> Void in - UIView.animateWithDuration(0.2) { - self.bigGulpButton.transform = CGAffineTransformMakeScale(1, 1) - self.smallGulpButton.transform = CGAffineTransformMakeScale(1, 1) - }; - } + func hideConfirmButtons() { + UIView.animateWithDuration(0.2, animations: { () -> Void in + self.bigConfirmButton.transform = CGAffineTransformMakeScale(0.001, 0.001) + self.smallConfirmButton.transform = CGAffineTransformMakeScale(0.001, 0.001) + }) { (_) -> Void in + UIView.animateWithDuration(0.2) { + self.bigGulpButton.transform = CGAffineTransformMakeScale(1, 1) + self.smallGulpButton.transform = CGAffineTransformMakeScale(1, 1) + }; } + } }