Reputation: 149
I want to make an API request from my watch app using openParenApplication
and handleWatchKitExtensionRequest
.
The API call from handleWatchKitExtensionRequest
would get data from the server and send that data to WatchKit app as a reply.
How can I accomplish this?
Upvotes: 0
Views: 1658
Reputation: 5939
Make sure you use a background task in your handleWatchKitExtensionRequest
method (check here for some advice: http://www.fiveminutewatchkit.com/blog/2015/3/11/one-weird-trick-to-fix-openparentapplicationreply), then simply call reply()
in the your API call's completion block (or similar) and pass the results.
Upvotes: 0
Reputation: 2034
In your Watch:
[WKInterfaceController openParentApplication:@{@«request» : «myRequest» } reply:^(NSDictionary *replyInfo, NSError *error) {
if (!error) {
// Parse your result here
}
else {
// Manage Error
}
}];
In app delegate
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *replyInfo))reply
{
if ([userInfo["request"] isEqualToString:"myRequest"]) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:userInfo[@«request »]]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imageData) {
reply(@{«result» : imageData});
}
else {
reply(@{«error» : @"error"});
}
});
});
}else {reply(@{}); }}
Upvotes: 1