Search code examples
objective-cswiftnsdictionaryapple-watch

Apple watch communicate with iOS app a new swift project vs to existing obj c project


1) I've managed to communicate from apple watch to iOS app using a complete swift project (iOS app in swift and Apple Watch target in swift)

Code:

In InterfaceController.swift

@IBAction func buttonPressed() {
    let watchMessage = ["SiteName" : "Tech-recipes"]

    WKInterfaceController.openParentApplication(watchMessage, reply: { (reply:[NSObject : AnyObject]!, error: NSError!) -> Void in

        if let message = reply["Message"] as? String{
            println(message)
        }
    })
}

in AppDelegate.swift

func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {

    if let siteName = userInfo["SiteName"] as? String{
        reply(["Message":"Hello from \(siteName)"])
    }

}

Output: "Hello from Tech-recipes"

2) However, when I want to integrate the apple watch target in swift to the exiting project in obj-c, it will crash and give me this error: "fatal error: unexpectedly found nil while unwrapping an Optional value"

In InterfaceController.swift

@IBAction func buttonPressed() {
    let watchMessage = ["SiteName" : "Tech-recipes"]

    WKInterfaceController.openParentApplication(watchMessage, reply: { (reply:[NSObject : AnyObject]!, error: NSError!) -> Void in

        if let message = reply["Message"] as? String{ //CRASH HERE!!!!
            println(message)
        }
    })
}

iPhoneAppDelegate.m

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply{

    // Performs task on phone here

    // Sending back a reply
    if ([[userInfo valueForKey:@"SiteName"] length]>0) {
        //NSMutableDictionary *reply = [[NSMutableDictionary alloc] init];
        [reply setValue:[NSString stringWithFormat:@"Hello from %@", [userInfo valueForKey:@"SiteName"]] forKey:@"Message"];
    }
}

Update:

--> Noticed that in handleWatchKitExtensionRequest: method the type for userInfo is different in swift and obj-c, in [NSObject : AnyObject]! and NSDictionary respectively. How to solve this?

--> Got an error in error: NSError!: [0] (null) @"NSLocalizedDescription" : @"The UIApplicationDelegate in the iPhone App never called reply() in -[UIApplicationDelegate application:handleWatchKitExtensionRequest:reply:]"


Solution

  • Solved it!

    Missed out the reply(aNsdictionary) in the app delegate