本文介绍了NSURLConnection 在更新到 Swift 2.0 后抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 2.0 更新之前,此代码非常适合使用 PHP 脚本从服务器下载我的 JSON 文件:

Before the Swift 2.0 Update this code worked perfectly to download my JSON File from the Server with a PHP Script:

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 要求我做一些更改.我做了,代码没有错误,但它总是抛出...

After the Update Xcode asked me to do some changes. I did and the code had no Error, but it always throws...

    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 中已被弃用.

Here's an example using the new NSURLSession - apparently NSURLConnection has been deprecated in 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()

我认为它非常干净,只是没有太多关于它的文档.如果您在使用它时遇到任何问题,请告诉我.

I think it's super clean, there's just not much documentation on it. Let me know if you have any trouble getting this to work.

这篇关于NSURLConnection 在更新到 Swift 2.0 后抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 03:19