Skip to content

Instantly share code, notes, and snippets.

@vanessaforney
Last active May 31, 2016 15:18
Show Gist options
  • Save vanessaforney/0e2b46028a27488e747bfb6c6fa27f7d to your computer and use it in GitHub Desktop.
Save vanessaforney/0e2b46028a27488e747bfb6c6fa27f7d to your computer and use it in GitHub Desktop.
//
// WatchSessionManager.swift
//
import WatchConnectivity
class WatchSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = WatchSessionManager()
private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
private var validSession: WCSession? {
if let session = session where session.paired && session.watchAppInstalled {
return session
}
return nil
}
var shelter: Shelter?
func startSessionWithShelter(shelter: Shelter) {
self.shelter = shelter
session?.delegate = self
session?.activateSession()
if shelter.dogsLoaded == true {
updateApplicationContext()
}
}
func sessionWatchStateDidChange(session: WCSession) {
if session.activationState == .Activated {
updateApplicationContext()
}
}
// Construct and send the updated application context to the watch.
func updateApplicationContext() {
let context = [String: AnyObject]()
// Now, compute the values from your model object to send to the watch.
do {
try WatchSessionManager.sharedManager.updateApplicationContext(context)
} catch {
print("Error updating application context")
}
}
}
// MARK: Application Context
extension WatchSessionManager {
// Sender
func updateApplicationContext(applicationContext: [String : AnyObject]) throws {
if let session = validSession {
do {
try session.updateApplicationContext(applicationContext)
} catch let error {
throw error
}
}
}
}
// MARK: Interactive Messaging
extension WatchSessionManager {
private var validReachableSession: WCSession? {
if let session = validSession where session.reachable {
return session
}
return nil
}
// Receiver
func session(session: WCSession, didReceiveMessage message: [String : AnyObject],
replyHandler: ([String : AnyObject]) -> Void) {
if message[Key.Request.ApplicationContext] != nil {
updateApplicationContext()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment