How can I awake my iPhone app in the background to

2019-07-14 07:47发布

问题:

I have a table in my Apple Watch app that is populated by data from the iPhone app.

On the iPhone app, I need to get this data from the internet. On the phone, the function is called retrieveData(). I also have a function called sendToWatch() that sends this data to the watch when the phone app is open.

I'd like to find a way to run retrieveData() and sendToWatch() without needing to open the phone app. I've looked into this for the past few hours, and it seems very complicated.

I've tried the openParentApp function that is on Apple's docs, but I have NO IDEA how to set it up or how to implement it. I've tried searching for tutorials online for the past few hours, but everything is already outdated and I've had no luck.

Does anybody know of any good tutorials for this?

回答1:

As you know, you can NOT use openParentApp in watchOS 2. You can use Watch Connectivity instead of openParentApp.

ref. http://www.kristinathai.com/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/

The following is one example.

1) Call sendMessage method from Apple Watch

WCSession.defaultSession().sendMessage(applicationDict,
   replyHandler: { ([String : AnyObject]) → Void in
      // Handle reply
   })
   errorHandler: { (NSError) → Void in
      // Handle error
});

2) didReceiveMessage method is called in your iPhone

Run retrieveData() and send data to Apple Watch in this method.

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
    // run retrieveData()

    // send data to Apple Watch
    replyHandler(["retrievedData" : data])
}

3) Receive data in replyHandler in Apple Watch

Good luck!