Search code examples
iosiphonewatchkitapple-watch

Launch host app from watch app


I know that the openParentApplication api in watch kit extension can open the host app in the background but not in the foreground.

I also tried using openUrl() api of NSExtensionContext as below:

NSExtensionContext *ctx = [[NSExtensionContext alloc] init];

NSURL *url = [NSURL URLWithString:@"myScheme://today"];
[ctx openURL:url completionHandler:^(BOOL success) {
    NSLog(@"fun=%s after completion. success=%d", __func__, success);
}];
[ctx completeRequestReturningItems:ctx.inputItems completionHandler:nil];

Here too the host app is not launched. Am I missing something? or is it not possible to launch the host app from watch kit extension?


Solution

  • If you need to open your parent app in the foreground, use Handoff!

    https://developer.apple.com/handoff/

    Example:

    Somewhere shared for both:

    static let sharedUserActivityType = "com.yourcompany.yourapp.youraction"
    static let sharedIdentifierKey = "identifier"
    

    on your Watch:

    updateUserActivity(sharedUserActivityType, userInfo: [sharedIdentifierKey : 123456], webpageURL: nil)
    

    on your iPhone in App Delegate:

    func application(application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
        if (userActivityType == sharedUserActivityType) {
            return true
        }
        return false
    }
    
    func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]!) -> Void) -> Bool {
        if (userActivity.activityType == sharedUserActivityType) {
            if let userInfo = userActivity.userInfo as? [String : AnyObject] {
                if let identifier = userInfo[sharedIdentifierKey] as? Int {
                    //Do something
                    let alert = UIAlertView(title: "Handoff", message: "Handoff has been triggered for identifier \(identifier)" , delegate: nil, cancelButtonTitle: "Thanks for the info!")
                    alert.show()
                    return true
                }
            }
        }
        return false
    }
    

    And finally (this step is important!!!): In your Info.plist(s)

    enter image description here