0

I am creating a glance and need to load some data from an API. I have written the following code but it does not allow me to asynchronously or synchronously request data in the glance controller.

let url = NSURL(string: "http://api.icndb.com/jokes/random")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    print(NSString(data: data!, encoding: NSUTF8StringEncoding)!)
}

The error occurs on NSURLConnection.sendAsynchronousRequest and says sendAsynchronousRequest(_:queue:completionHandler:) is unavailable. I remember that have read somewhere that you should not load data in a glance, and if this is the case how should I load the data each time the glance appears?

My questions are:

How can I load data over HTTP in a apple watch glance? And if it is impossible to load HTTP data in a glance, how else should I do it?

Ryan Westcott
  • 199
  • 3
  • 14

1 Answers1

2

NSURLConnection should work, but since it is deprecated, I would recommend using NSURLSession instead.

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
    // handle the response
}
task.resume()

A good place to call it is the awakeWithContext method of your glances interface controller. I have done it and it works fine on a glance.

Adam
  • 26,549
  • 8
  • 62
  • 79