How can I awake my iPhone app in the background to run a function and return the results to Apple Watch?

孤人 提交于 2019-12-11 04:26:33

问题


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!



来源:https://stackoverflow.com/questions/32911706/how-can-i-awake-my-iphone-app-in-the-background-to-run-a-function-and-return-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!