2

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?

Think Graphical
  • 351
  • 1
  • 11

2 Answers2

2

While Frederick's advice was solid advice for WatchKit 1, openParentApplication:reply is no longer available in WatchKit 2. With WatchKit 2, you would instead definitely open the NSURLSession in the WatchKit App Extension itself, because using a WCSession means that the URL would only be opened if and when the iPhone application itself is running, either in the foreground or if it happens to still be running in the background because the system has not closed it.

It is possible that the problems you were experiencing were because you needed to add the 'Allows Arbitrary Loads' property on the WatchKit App Extension. See discussion in this possibly related thread: NSURLSession returns data as Null on Watch OS2 using Objective-C

Community
  • 1
  • 1
Duncan Babbage
  • 19,972
  • 4
  • 56
  • 93
1

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.

  • This seems to work, only thing I had to use is WCSession sendMessage instead of openParentApplication:reply because of watchOS2. – Think Graphical Jun 26 '15 at 07:12