json - Swift HTTP 请求在模拟器上有效,但在真实设备上无效

标签 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_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
    }
}

如果由于对 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()

关于json - Swift HTTP 请求在模拟器上有效,但在真实设备上无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867292/

相关文章:

ios - 如何在 jenkins 上运行 ios 模拟器进行 ui 自动化测试

ios - Image.xcassets 在模拟器上呈现奇怪

angularjs - Angular、Chrome - 所有请求都停滞了大约 450 毫秒

Apache 上的 Django - 防止 504 网关超时

java - 是否可以使用@RequestMapping检查 header 的值

php - 将其存储为对象

php - 创建一个表单以使用 MySQL 更新 JSON 数据

java - 通过在java中读取mySQL表创建JSON文件

C# 转换 Unicode 字符

ios7 - iOS 7 模拟器日语键盘词典位于何处?