Roel
Roel

Reputation: 63

watchOS 2 on device doesn't read NSData

In my watchOS 2 Apple Watch WatchKit Extension, I make use NSURL and NSData to request a URL and retrieve the JSON it sends. However, this does only work in the simulator. At first I had a problem because I was using an untrusted address (an internal IP address), but after adding some keys and values to Info.plist, this problem was fixed. To be completely sure the URL was trusted, I used an open URL from the GitHub API (https://api.github.com/users/mralexgray/repos). I use the following code to retrieve the response:

var responseData: NSData? = nil
if let url = NSURL(string: "https://api.github.com/users/mralexgray/repos") {
    if let data = NSData(contentsOfURL: url){
        responseData = data
    }
}

On my watchOS 2 simulator, responseData is filled correctly, but on my Apple Watch device, it looks like line number 3 and its body are just getting skipped. Is this a problem, feature or am I doing something wrong?

Upvotes: 4

Views: 327

Answers (1)

pinxue
pinxue

Reputation: 1746

It sounds like a bug in NSData method, contentsOfURL:option:error: says file cannot open.

NSURLSession works fine.

NSURL * url = [NSURL URLWithString:@"https://api.github.com/users/mralexgray/repos"];

NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
                                      dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                          NSLog(@"data size %ld", (unsigned long)data.length);
                                      }];

[downloadTask resume];

Upvotes: 2

Related Questions