WatchOS2 WCSession sendMessage doesn't wake iPhone on background

后端 未结 3 1358
悲&欢浪女
悲&欢浪女 2021-01-04 04:17

This is being tested on both Simulator and real physical device iphone5s. I tried to use WCSession sendMessage to communicate from WatchOS2 extension to iPhone iOS9 code. It

3条回答
  •  天命终不由人
    2021-01-04 04:54

    It is important that you activate the WCSession in your AppDelegate didFinishLaunchingWithOptions method. Also you have to set the WCSessionDelegate there. If you do it somewhere else, the code might not be executed when the system starts the killed app in the background.

    Also, you are supposed to send the reply via the replyHandler. If you try to send someway else, the system waits for a reply that never comes. Hence the timeout error.

    Here is an example that wakes up the app if it is killed:

    In the WatchExtension:

    Setup the session. Typically in your ExtensionDelegate:

    func applicationDidFinishLaunching() {
        if WCSession.isSupported() {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        }
    }
    

    And then send the message when you need something from the 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)
        }
    }
    

    In the iPhone App:

    Same session setup, but this time also set the delegate:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ...
        if WCSession.isSupported() {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        }
    }
    

    And then implement the delegate method to send the reply to the watch:

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
        replyHandler(["message": "Hello Watch!"])
    }
    

    This works whenever there is a connection between the Watch and the iPhone. If the app is not running, the system starts it in the background.

    I don't know if the system waits long enough until you received your data from iCloud, but this example definitely wakes up the app.

提交回复
热议问题