openParentApplication仅在应用程序在前台运行时才有效 [英] openParentApplication only works when the app is running in the foreground
问题描述
我正在尝试使用 openParentApplication
从服务器请求数据并在监视扩展中使用它,但是当主应用程序是没有在前台运行。当主应用程序在前台运行时,一切正常。
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屋!