openParentApplication仅在应用程序在前台运行时才有效

moh*_*ili 4 iphone objective-c ios apple-watch watchkit

我试图通过使用openParentApplication并在手表扩展中使用来从服务器请求数据,但是当主应用程序没有在前台运行时我没有得到任何回复.当主应用程序在前台运行时,一切正常.

Gre*_*reg 10

之前我遇到过这个问题,原因是你没有注册长时间运行的后台操作,系统将其终止.这就是我对此进行排序的方法,请参阅注解说明,这些都在AppDelegate文件中,并且在swift中,但您可以轻松地将其移植到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()
    }
}
Run Code Online (Sandbox Code Playgroud)