Json Swift HTTP请求可以在模拟器上工作,但不能在真实设备上工作

Json Swift HTTP请求可以在模拟器上工作,但不能在真实设备上工作,json,ios-simulator,httprequest,watchos-2,Json,Ios Simulator,Httprequest,Watchos 2,我创建了一个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_r

我创建了一个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
    }
}
func price\u request()->NSData?{
guard let url=NSURL(字符串:https://api.xxxxx.com/xxx.php)其他{
归零
}
guard let data=NSData(contentsOfURL:url)else{
打印(“[错误]连接有未指定的错误”)
归零
}
打印(“[连接]正常,数据已正确下载”)
返回数据
}
func json_parseData(数据:NSData)->NSDictionary?{
做{
让json:AnyObject=try NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions.MutableContainers)作为!字典
打印(“[JSON]确定!”)
返回(json作为?NSDictionary)
}接住{
打印(“[ERROR]解析json数据时出错”)
归零
}
}
我还尝试添加应用程序传输安全旁路,如果由于请求HTTPS URL而不需要它,但它不起作用

你能帮帮我吗


谢谢

尝试使用NSURLSession获取数据

//declare data task
var task: URLSessionDataTask?

//setup the session
let url = URL(string:"https://url.here")!
let session = URLSession(configuration: URLSessionConfiguration.default)

 task = session.dataTask(with: url){ (data, res, error) -> Void in
        if let e = error {
            print("dataTaskWithURL fail: \(e.localizedDescription)")
            return
        }
        if let d = data {
           //do something
        }
    }
    task!.resume()

谢谢,我会在几小时内尝试。我会给你的代码发送一些修正,比如将NSUrl改为URL。