Skip to content
This repository has been archived by the owner on Oct 15, 2018. It is now read-only.

Commit

Permalink
Fix watch connectivity
Browse files Browse the repository at this point in the history
  • Loading branch information
andreamazz committed Nov 12, 2015
1 parent f27c036 commit 65654df
Show file tree
Hide file tree
Showing 15 changed files with 242 additions and 138 deletions.
7 changes: 4 additions & 3 deletions Gulps WatchKit Extension/ComplicationController.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ClockKit


class ComplicationController: NSObject, CLKComplicationDataSource {

func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
Expand Down Expand Up @@ -32,11 +33,11 @@ class ComplicationController: NSObject, CLKComplicationDataSource {

func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) {
var percentage = 0
if let storedPercentage = EntryHelper.sharedHelper.percentage() {
if let storedPercentage = WatchEntryHelper.sharedHelper.percentage() {
percentage = storedPercentage
}

if (complication.family == .UtilitarianSmall) {
if complication.family == .UtilitarianSmall {
let smallFlat = CLKComplicationTemplateUtilitarianSmallFlat()
smallFlat.textProvider = CLKSimpleTextProvider(text: "\(percentage)%")
smallFlat.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "complication")!)
Expand Down Expand Up @@ -66,7 +67,7 @@ class ComplicationController: NSObject, CLKComplicationDataSource {
}

// MARK: - Time Travel

func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler(.None)
}
Expand Down
38 changes: 0 additions & 38 deletions Gulps WatchKit Extension/EntryHelper.swift

This file was deleted.

46 changes: 29 additions & 17 deletions Gulps WatchKit Extension/ExtensionDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import WatchKit
import WatchConnectivity
import ClockKit

class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {

Expand All @@ -17,31 +18,33 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
private func setupNotificationCenter() {
notificationCenter.addObserverForName(NotificationWatchGulpAdded, object: nil, queue: nil) {
(notification: NSNotification) in
if let data = notification.object as? String {
let cache = EntryHelper.sharedHelper.cachedData(newData: data)
self.sendCachedData(cache)
}
self.sendApplicationContext()
self.reloadComplications()
}
}

// MARK: - Watch Connectivity

private func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
guard WCSession.isSupported() else {
return
}

let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}

private func sendCachedData(data: [[String: AnyObject]]) {
if WCSession.isSupported() {
do {
let dictionary = [Constants.WatchContext.Cached.key(): data]
try WCSession.defaultSession().updateApplicationContext(dictionary)
} catch {
print("Unable to send cache data to WCSession: \(error)")
}
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)")
}
}

Expand All @@ -51,11 +54,20 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
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 {
EntryHelper.sharedHelper.saveSettings(goal: goal, current: current, small: small, big: big)
WatchEntryHelper.sharedHelper.saveSettings(goal: goal, current: current, small: small, big: big)
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NotificationContextReceived, object: nil)
self.reloadComplications()
}
}
}

func reloadComplications() {
if let complications: [CLKComplication] = CLKComplicationServer.sharedInstance().activeComplications {
complications.forEach({
(complication: CLKComplication) in
CLKComplicationServer.sharedInstance().reloadTimelineForComplication(complication)
})
}
}
}
2 changes: 1 addition & 1 deletion Gulps WatchKit Extension/GlanceController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class GlanceController: WKInterfaceController {

override func willActivate() {
super.willActivate()
if let percentage = EntryHelper.sharedHelper.percentage() {
if let percentage = WatchEntryHelper.sharedHelper.percentage() {
percentageLabel.setText("\(percentage)%")
}
}
Expand Down
5 changes: 3 additions & 2 deletions Gulps WatchKit Extension/InterfaceController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ typealias InterfaceHelper = InterfaceController
private extension InterfaceHelper {

func reloadAndUpdateUI() {
let percentage = EntryHelper.sharedHelper.percentage() ?? 0
let percentage = WatchEntryHelper.sharedHelper.percentage() ?? 0
var delta = percentage - Int(previousPercentage)
if (delta < 0) {
// animate in reverse using negative duration
Expand All @@ -77,7 +77,8 @@ private extension InterfaceHelper {
}

func updateWithGulp(gulp: String) {
EntryHelper.sharedHelper.addGulp(gulp)
WatchEntryHelper.sharedHelper.addGulp(gulp)
reloadAndUpdateUI()
NSNotificationCenter.defaultCenter().postNotificationName(NotificationWatchGulpAdded, object: gulp)
}
}
Expand Down
66 changes: 66 additions & 0 deletions Gulps WatchKit Extension/WatchEntryHelper.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import Foundation

class WatchEntryHelper {
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 quantity = userDefaults.doubleForKey(Constants.WatchContext.Current.key())
let portion = userDefaults.doubleForKey(portion)
userDefaults.setObject(NSDate(), forKey: Constants.WatchContext.Date.key())
userDefaults.setDouble(quantity + portion, forKey: Constants.WatchContext.Current.key())
userDefaults.synchronize()
}

func applicationContext() -> [String: Double] {
let quantity = userDefaults.doubleForKey(Constants.WatchContext.Current.key())
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())]
}

/**
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 quantity = userDefaults.doubleForKey(Constants.WatchContext.Current.key())

guard quantity != 0 else {
return nil
}

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
}
}

let goal = userDefaults.doubleForKey(Constants.Gulp.Goal.key())
return Int((quantity / goal) * 100.0)
}
}
Loading

0 comments on commit 65654df

Please sign in to comment.