我创建了一个watchOS应用程序,它从API请求值并在标签上显示。 它在模拟器中工作得很好,但是当我在Apple Watch上执行它时会崩溃并出现以下错误:
[ERROR] There is an unspecified error with the connection
fatal error: unexpectedly found nil while unwrapping an Optional value
第一个错误是由我的代码生成的。
我写的代码是:
func price_request() -> NSData? {
guard let url = NSURL(string: "https://api.xxxxx.com/xxx.php") else {
return nil
}
guard let data = NSData(contentsOfURL: url) else {
print("[ERROR] There is an unspecified error with the connection")
return nil
}
print("[CONNECTION] OK, data correctly downloaded")
return data
}
func json_parseData(data: NSData) -> NSDictionary? {
do {
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>
print("[JSON] OK!")
return (json as? NSDictionary)
} catch _ {
print("[ERROR] An error has happened with parsing of json data")
return nil
}
}
我还尝试添加App Transport Security旁路(如果由于对HTTPS URL的请求而不需要它,但它不起作用。)
你能帮帮我吗?
谢谢
答案 0 :(得分:2)
尝试使用NSURLSession获取数据......
//declare data task
var task: NSURLSessionDataTask?
//setup the session
let url = NSURL(string:"https://url.here")!
let conf = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: conf)
task = session.dataTaskWithURL(url) { (data, res, error) -> Void in
if let e = error {
print("dataTaskWithURL fail: \(e.debugDescription)")
return
}
if let d = data {
//do whatever
})
}
}
task!.resume()