Search code examples
swiftwatchkitnsurlsession

Problems with Watchkit Extension NSURLSession in Swift


I'm trying to call my local API to turn off my house lighting from my watch, but I'm having trouble with calling a url from within the watchkit extension.

In my ViewController (iPhone app) I've got exactly the same code (which works), but somehow it doesn't work when I call it in the InterfaceController from the Watchkit Extension.

@IBAction func confirmTapped() {

    let url = NSURL(string: "http://homeserver.local/api/lights/4/0")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    }

    task!.resume()
}

I've also attached a gist: https://gist.github.com/f72125cd4678069af7af.git

Am I missing something obvious?


Solution

  • I don't know if it's a good thing to start a NSURLSession from within the Watch extension. If the request takes to long, it will be cancelled.

    Maybe you could ping the watch via openParentApplication:reply and handle the NSURLSession on your iPhone app.