openParentApplication 仅在应用程序在前台运行时有效 [英] openParentApplication only works when the app is running in the foreground
问题描述
我正在尝试使用 openParentApplication
从服务器请求数据并在 watch 扩展中使用它,但是当主应用程序没有在前台运行时我没有得到任何返回.当主应用程序在前台运行时,一切正常.
I'm trying to request data from the server by using openParentApplication
and use it in the watch extension, but I don't get anything back when the main app is not running in the foreground. When the main app is running in the foreground everything works fine.
推荐答案
我之前遇到过这个问题,原因是你没有注册长时间运行的后台操作,系统杀死了它.这就是我的排序方式,请参阅注释以获取解释,这一切都在 AppDelegate 文件中,并且是 swift 的,但您可以轻松地将其移植到 Objective-c:
I had this issue before and the reason was that you haven't registered long running background operation and the system kill it. This is how I sorted this, please see comments for explanations, this is all in AppDelegate file and it in swift but you can easily port it to Objective-c:
private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
func registerBackgroundTask() {
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
[unowned self] in
self.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
// MARK: - Watch Kit
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
registerBackgroundTask()
// Fetch the data from the network here
// In the competition handler you need to call:
// the nil can be replaced with something else you want to pass back to the watch kit
reply(nil)
if self.backgroundTask != UIBackgroundTaskInvalid {
self.endBackgroundTask()
}
}
这篇关于openParentApplication 仅在应用程序在前台运行时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!