WatchOS 2 - 执行HTTP POST?

时间:2016-07-19 18:02:10

标签: swift nsurlsession apple-watch

我知道WatchOS 2+支持NSURLSession进行一些简单的调用。我知道我可以使用iOS配套应用程序为我执行POST并将其传回 - 但手表可以执行那些POST调用吗?我试过了,操作失败了。可能是因为线程?不支持POST?

let thisSpeakerIP = "192.168.1.170"
let url = NSURL(string:"http://\(thisSpeakerIP):8090/key")
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "<key state=\"press\" sender=\"Gabbo\">PRESET_4</key>"

request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
    (let data, let response, let error) in
    guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
        print("test watch error")
        return
    }
    let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("dataString: '\(dataString!)'")

    let action = WKAlertAction(title: "OK", style: WKAlertActionStyle.Default, handler: { () -> Void in
        //
    })

    dispatch_async(dispatch_get_main_queue()) {
        self.presentAlertControllerWithTitle("NSURLSession", message: "Got \(dataString!)", preferredStyle: WKAlertControllerStyle.SideBySideButtonsAlert, actions: [action])
    }
}
task.resume()

0 个答案:

没有答案