简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM