user4800940
user4800940

Reputation:

How to trigger communication with backend from Apple Watch?

I want to click on a push notification on my Apple Watch trigger communication with backend and show the results in a table on my Apple Watch.

I know how to show the result in a table on my Apple Watch. I also know the openParentApplication:reply: method.

But if I want to trigger my backend communication in application:handleWatchKitExtensionRequest:reply: I get a error that reply() is never called. It seems that iOS kill this method if it takes to much time.

If I test application:handleWatchKitExtensionRequest:reply: with a hard coded dictionary with only one entry, all works fine.

That is the recommended way to do this?

In my opinion I should do something in NotificationController.swift in didReceiveRemoteNotification method and app group but how can I trigger the backend communication on my iPhone?

UPDATE:

Part of my code in AppDelefate.swift:

    func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
        var workaround: UIBackgroundTaskIdentifier?
        workaround = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            UIApplication.sharedApplication().endBackgroundTask(workaround!)
        })

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
            UIApplication.sharedApplication().endBackgroundTask(workaround!)
        })

        var realBackgroundTaks: UIBackgroundTaskIdentifier?
        realBackgroundTaks = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({                
            reply(nil)
            UIApplication.sharedApplication().endBackgroundTask(realBackgroundTaks!)
        })

        let testDict = ["Hello" : "World"]
        reply(testDict)

        UIApplication.sharedApplication().endBackgroundTask(realBackgroundTaks!)
    }

This code works fine. But if I change testDict to the backend communication code this method will killed.

Upvotes: 1

Views: 712

Answers (2)

user4800940
user4800940

Reputation:

Today I found the solution for my problem. You can not pass custom objects in the reply dictionary, you have to use primitive types.

The splution is described on the following page from Kristina Thai.

http://realm.io/news/watchkit-mistakes/

Upvotes: 1

bgilham
bgilham

Reputation: 5939

You'll need to start a background task on the iPhone to ensure your app isn't killed in the background before your API request can complete. I've shared some resources in a similar answer here: https://stackoverflow.com/a/29848521/3704092

Upvotes: 0

Related Questions