Reputation: 1581
I've faced an issue while trying to synchronise iPhone app and WatchKit app.
The thing is - my WatchKit app tableView
is appended by the data array from iPhone.
I'm using interactive messaging from Watch Connectivity framework
Establishing session
if(WCSession.isSupported()){
self.session = WCSession.defaultSession()
self.session.delegate = self
self.session.activateSession()
}
sending message to WatchKit app
do {
let dataDict = ["data": dictionary1]
try WCSession.defaultSession().updateApplicationContext(dataDict)
}
catch {
print(error)
}
and this is how i receive the message on the Watch
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if let retrievedArray1 = applicationContext["data"] as? [Int : Bool] {
self.arrayOnWatch = retrievedArray1
}
}}
It works well with one exception - i cannot get the data array UNTIL i launch the app on the iPhone, which isn't a solution in my case.
Any ideas on how to transfer and receive the message without opening the actual phone app?
Thank you.
Upvotes: 2
Views: 257
Reputation: 27620
Using the application context does not work for your case, because it needs the iPhone app to actively set the application context.
You can use WatchKit's sendMessage
to let the watch ask the iPhone app for data.
In your ExtensionDelegate after activating the connection send a message to the iPhone app:
if WCSession.defaultSession().reachable {
let messageDict = ["message": "hello iPhone!"]
WCSession.defaultSession().sendMessage(messageDict, replyHandler: { (replyDict) -> Void in
print(replyDict)
}, errorHandler: { (error) -> Void in
print(error)
}
}
This will wake up your iPhone app in the background if the iPhone app is not running.
In your iPhone app's AppDelegate implement the corresponding WCSessionDelegate method (after activating the session in didFinishLauncingWithOptions:
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
replyHandler(["message": "Hello Watch!"])
}
Just send your data instead of "Hello Watch!" and your watch will have the data even if the iPhone app is not running.
Upvotes: 2