在 Swift 2.0 Update之前,这段代码可以很好地从服务器上用 PHP脚本下载我的JSON文件: let url = NSURL(string: webAdress)let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheDatavar request = NSMut
let url = NSURL(string: webAdress) let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0) var response: NSURLResponse? = nil var error: NSError? = nil let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
更新后Xcode要求我做一些更改.我做了,代码没有错误,但它总是抛出……
let url = NSURL(string: webAdress) let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0) var response: NSURLResponse? = nil var reply = NSData() do { reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch { print("ERROR") }
期待您的解决方案!
这是使用新NSURLSession的示例 – 显然NSURLConnection已在iOS 9中弃用.let url = NSURL(string: webAddress) let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0) let session = NSURLSession.sharedSession() session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in print(data) print(response) print(error) })?.resume()
我认为它非常干净,没有太多关于它的文档.如果您在使用此功能时遇到任何问题,请与我们联系.