Skip to content

Instantly share code, notes, and snippets.

@vanessaforney
Last active May 31, 2016 15:20
Show Gist options
  • Save vanessaforney/0142ab8e72ad8a4dee65998fe753f4bd to your computer and use it in GitHub Desktop.
Save vanessaforney/0142ab8e72ad8a4dee65998fe753f4bd to your computer and use it in GitHub Desktop.
//
// PhoneSessionManager.swift
//
import WatchConnectivity
class PhoneSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = PhoneSessionManager()
// Reference to the model object.
private var shelterSummary = ShelterSummary()
private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
func startSession() {
session?.delegate = self
session?.activateSession()
}
func requestApplicationContext() {
// Send a message with a key that your phone expects. You can organize your constants in a
// series of structs like I did, or hard code a string instead of Key.Request.ApplicationContext.
sendMessage([Key.Request.ApplicationContext: true], replyHandler: nil, errorHandler: nil)
}
func sessionReachabilityDidChange(session: WCSession) {
// Request new application context when reachability changes.
requestApplicationContext()
}
}
// MARK: Application Context
extension PhoneSessionManager {
// Receiver
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
dispatch_async(dispatch_get_main_queue()) { [weak self] in
// Update the model object.
self?.shelterSummary.updateFromContext(applicationContext)
}
}
}
// MARK: Interactive Messaging
extension PhoneSessionManager {
// App has to be reachable for live messaging.
private var validReachableSession: WCSession? {
if let session = session where session.reachable {
return session
}
return nil
}
// Sender
func sendMessage(message: [String : AnyObject], replyHandler: (([String : AnyObject]) -> Void)? = nil,
errorHandler: ((NSError) -> Void)? = nil) {
validReachableSession?.sendMessage(message, replyHandler: replyHandler, errorHandler: errorHandler)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment