ios - sendAsynchronousRequest 在 iOS 9 中被弃用,如何修改代码来修复

标签 ios swift ios9

以下是我遇到问题的代码:

func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in

        if ((error) != nil)
        {
            callback(feed: nil, error: error)
        }
        else
        {
            self.callbackClosure = callback

            let parser : NSXMLParser = NSXMLParser(data: data!)
            parser.delegate = self
            parser.shouldResolveExternalEntities = false
            parser.parse()
        }
    }
}

从 iOS 9 开始,这已被弃用,并告诉我改用 dataTaskWithRequest。谁能帮我用 dataTask 更改 sendAsync,我不知道该怎么做。

最佳答案

像下面这样使用NSURLSession

对于 objective-c

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] resume];

对于 Swift,

    var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var params = ["username":"username", "password":"password"] as Dictionary<String, String>

    request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")})

    task.resume()

对于异步查询,来自 Apple docs

Like most networking APIs, the NSURLSession API is highly asynchronous. It returns data in one of two ways, depending on the methods you call:

To a completion handler block that returns data to your app when a transfer finishes successfully or with an error.

By calling methods on your custom delegate as the data is received.

By calling methods on your custom delegate when download to a file is complete.

关于ios - sendAsynchronousRequest 在 iOS 9 中被弃用,如何修改代码来修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30935304/

相关文章:

ios - 带 UITableView 的 UITabBar - 我可以正确看到表格,但无法选择一行

iphone - 初始化中的 startUpdatingLocation

swift - 裁剪图像出现错误

arrays - 如何在swift代码中保存一组类

ios - 在 swift 项目的 Storyboard中使用 Objective-C 类作为自定义类

iOS 9 中的数据包隧道提供程序

ios - 将 CIFilter 应用于视频文件并保存

ios - Swift 测试无法在 Objective-C VC 上找到 Swift 类属性

ios - 如果应用程序在 iOS 9 上处于后台,则不会出现推送通知

ios - 每周特定日期的本地通知