sendAsynchronousRequest 在 iOS 9 中已弃用,如何更改代码以修复

Posted

技术标签:

【中文标题】sendAsynchronousRequest 在 iOS 9 中已弃用,如何更改代码以修复【英文标题】:sendAsynchronousRequest was deprecated in iOS 9, How to alter code to fix 【发布时间】:2015-09-05 06:27:38 【问题描述】:

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

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,我不知道怎么做。

【问题讨论】:

我认为 NSURLConnection 在 iOS8 中已被弃用。你应该从 iOS7 开始使用 NSURLSession。 有什么问题?您对the documentation 理解有困难吗? 是的,我不知道如何将其转换为使用dataTaskWtihReqeust,我不知道我需要更改什么。 我同意 DarkDust,NSURSession 很容易理解。看看Ray的教程raywenderlich.com/51127/nsurlsession-tutorial 光顾我也无济于事,但我是 swift 新手,更喜欢看到答案,然后在看到你所做的事情时有灵光乍现的时刻。我会看看但是这是Objectvice-C,知道swift中的任何教程吗? 【参考方案1】:

使用NSURLSession 代替如下,

对于 Objective-C

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

  ] resume];

对于斯威夫特,

    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

与大多数网络 API 一样,NSURLSession API 异步。它以两种方式之一返回数据,具体取决于 你调用的方法:

到一个完成处理程序块,该块将数据返回到您的应用程序,当 传输成功或出错。

通过在接收数据时调用自定义委托上的方法。

通过在下载到文件时调用自定义委托上的方法 完成。

【讨论】:

如何确保请求异步运行? @Supertecnoboff,我刚刚更新了我的答案。如果您仍有任何疑问,请告诉我。 我在 &err 语句中得到一个错误:调用中的额外参数“错误” 你好 Nilesh,在这个链接上的 Linkedin 上找到我..linkedin.com/in/khushal-patel-6108537b【参考方案2】:

Swift 实现

let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)  (data, response, error) -> Void in


【讨论】:

别忘了你需要在你的dataTaskWithRequest 上调用resume(),否则它什么也做不了。【参考方案3】:

斯威夫特 3.0

var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
let session = URLSession.shared

session.dataTask(with: request) data, response, err in
    print("Entered the completionHandler")
.resume()

【讨论】:

【参考方案4】:

这是 swift 2.1 版本:

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

let 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")

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

task.resume()

【讨论】:

感谢您的更新。苹果的开发环境开始令人困惑。一切都过时了!【参考方案5】:

Swift 2.0:

旧的(下面替换为新的):

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue())  (response, data, error) -> Void in

// Code


新:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) data, response, error in

// Code


task.resume()

【讨论】:

【参考方案6】:

斯威夫特 4

let params = ["email":"email@email.com", "password":"123456"] as Dictionary<String, String>

var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler:  data, response, error -> Void in

    do 
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
        print(json)
     catch 
        print("error")
    

)

task.resume()

【讨论】:

【参考方案7】:

使用 swift 3.1

let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL)
    let session = URLSession.shared
    request.httpMethod = "POST"

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

    request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

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

    let task = session.dataTask(with: request as URLRequest, completionHandler: data, response, error -> Void in
        print("Response: \(String(describing: response))"))

    task.resume()

【讨论】:

【参考方案8】:

用一个例子来说明,弃用的替代代码:

sendAsynchronousRequest(_:queue:completionHandler:)' 在 iOS 9.0 中已弃用:使用 [NSURLSession dataTaskWithRequest:completionHandler:]

在 Swift 2.1 及更高版本中经过测试和工作。

import UIKit

class ViewController: UIViewController 


    @IBOutlet var theImage: UIImageView!


    override func viewDidLoad() 
        super.viewDidLoad()


        let url = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg")


        let task = NSURLSession.sharedSession().dataTaskWithURL(url!)  (data, response, error) -> Void in

            if error != nil 
                print("thers an error in the log")
             else 

                dispatch_async(dispatch_get_main_queue()) 
                let image = UIImage(data: data!)
                self.theImage.image = image

                
            

        

        task.resume()

    


//在 ViewControllers ImageView 上显示一个图像。连接ImageView的一个outlet

【讨论】:

【参考方案9】:

这是带有 JSONSerialised 数据的 Nilesh Patel's Answer 的 SWIFT3.0 版本

let url = URL(string: "<HERE GOES SERVER API>")!
            var request = URLRequest(url: url)
            request.httpMethod = "POST" //GET OR DELETE etc....
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("<ValueforAuthorization>", forHTTPHeaderField: "Authorization")
            let parameter = [String:Any]() //This is your parameters [String:Any]
            do 
                let jsonData = try JSONSerialization.data(withJSONObject: parameter, options: .prettyPrinted)
                // here "jsonData" is the dictionary encoded in JSON data
                request.httpBody = jsonData
                let session = URLSession(configuration: .default)
                let task = session.dataTask(with: request, completionHandler:  (incomingData, response, error) in
                    if let error = error 
                        print(error.localizedDescription)
                        print(request)
                    else if let response = response 
                        print(response)
                    else if let incomingData = incomingData 
                        print(incomingData)
                    
                )
                task.resume()

             catch 
                print(error.localizedDescription)
            

【讨论】:

【参考方案10】:

斯威夫特 4.2

这对我有用:

func loadImageFromURL(URL: NSURL) 
    let request = URLRequest(url: URL as URL)
    let task = URLSession.shared.dataTask(with: request)  (data, response, error) in
        if let imageData = data 
            DispatchQueue.main.async 
                self.imageView.image = UIImage(data: imageData)
            
        
    
    task.resume()

我不得不添加“DispatchQueue.main.async ”,因为我有一个运行时警告,因为只有主线程应该修改 UI 元素。

【讨论】:

以上是关于sendAsynchronousRequest 在 iOS 9 中已弃用,如何更改代码以修复的主要内容,如果未能解决你的问题,请参考以下文章

sendAsynchronousRequest 使 UI 冻结

sendAsynchronousRequest 在 iOS 9 中已弃用,如何更改代码以修复

返回方法中的 sendAsynchronousRequest 和 completionHandler

NSURLConnection sendAsynchronousRequest 在某些刷新请求上没有命中完成处理程序

NSURL Connection sendAsynchronousRequest 如何保存响应?

ios:NSURLConnection sendAsynchronousRequest 为啥不起作用?