Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openParentApplication only works when the app is running in the foreground

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.

like image 442
Mo Al Waili Avatar asked Dec 14 '22 13:12

Mo Al Waili


1 Answers

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()
    }
}
like image 71
Greg Avatar answered May 07 '23 12:05

Greg