从 WatchKit 2.0 连接到外部 URL

Connecting to external URL from WatchKit 2.0

我想从 REST 后台在 WatchKit 界面中加载一些信息。有没有一些快速的方法来执行主机 iOS 应用程序传递的 URL 请求,或者我必须利用裸露的 WatchConnectivity 功能制定一个特定的协议?

您应该直接在 WatchKit 扩展中使用 NSURLSession。

NSURLSession 可以与 Watchkit 一起正常工作,但如果相关的话,您还需要在 Watchkit 扩展上添加 Allows Arbitrary Loads。

请看这个post,

NSURLSession returns data as Null on Watch OS2 using Objective-C

我正在使用 sendMessageData:replyHandler:,但我无法让它正常工作。相关票在:

尽管 Apple 的示例在 swift 中,请参见 https://developer.apple.com/videos/play/wwdc2015-228/?time=345 ,但我在 NSProcessInfo 包装器的 obejctive-c utlis 中粘贴了一个片段。

Apple 的示例也使用了 Semaphore 的,如果扩展被置于休眠状态,我在下面省略了。

按照以下模式,您可以直接从手表上点击所需的服务。

NSProcessInfo *processInfo = [NSProcessInfo processInfo];

[processInfo performExpiringActivityWithReason:@"networkReq" usingBlock:^(BOOL expired) {
    if (!expired){            
        NSLog(@"we have an assertion");        
        NSTimeInterval secondsInThreeHours = 3 * 60 * 60;
        NSURL *forecast = [NSURL URLWithString:@"http::address"];

        NSURLSession *session = [NSURLSession sharedSession];
        [[session dataTaskWithURL:forecast
                completionHandler:^(NSData *data,
                                    NSURLResponse *response,
                                    NSError *error) {
                    // handle response
         }] resume];
    else{

        NSLog(@"Not background assertion or we are out of time");
    }
}];