iOS 9中不推荐sendAsynchronousRequest

iOS 9中不推荐sendAsynchronousRequest,ios,swift2,ios9,Ios,Swift2,Ios9,我正在尝试将代码从Swift 1.2更改为Swift 2.0,但对于“sendAsynchronousRequest”,我遇到了一些问题,因为它总是显示警告,因为它已被弃用。我尝试过使用这篇文章中的另一个解决方案:但它仍然不起作用,我再次收到同样的警告 我必须在代码中更改什么才能解决此警告?警告如下: sendAsynchronousRequest在iOS 9中已被弃用,请使用dataTaskWithRequest:completionHandler 这是我的代码: func collectio

我正在尝试将代码从Swift 1.2更改为Swift 2.0,但对于“sendAsynchronousRequest”,我遇到了一些问题,因为它总是显示警告,因为它已被弃用。我尝试过使用这篇文章中的另一个解决方案:但它仍然不起作用,我再次收到同样的警告

我必须在代码中更改什么才能解决此警告?警告如下:

sendAsynchronousRequest在iOS 9中已被弃用,请使用dataTaskWithRequest:completionHandler

这是我的代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // try to reuse cell
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MarcaCollectionViewCell

    // get the deal image
    let currentImage = marcas[indexPath.row].imagen
    let unwrappedImage = currentImage
    var image = self.imageCache[unwrappedImage]
    let imageUrl = NSURL(string: marcas[indexPath.row].imagen)

    // reset reused cell image to placeholder
    cell.marcaImageView.image = UIImage(named: "")

    // async image
    if image == nil {

        let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
            if error == nil {

                image = UIImage(data: data!)

                self.imageCache[unwrappedImage] = image
                dispatch_async(dispatch_get_main_queue(), {
                    cell.marcaImageView.image = image

                })
            }
            else {

            }
        })
    }

    else {
        cell.marcaImageView.image = image
    }

    return cell

}

正如警告所警告的,NSURLConnection已断开。会议万岁

let session = NSURLSession.sharedSession()
let urlString = "https://api.yoursecureapiservergoeshere.com/1/whatever"
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
  print("done, error: \(error)")
}
dataTask.resume()

使用
NSURLSession
代替如下所示

目标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>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

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

task.resume()
var-request=NSMutableURLRequest(URL:NSURL(字符串:“您的URL”))
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
var params=[“用户名”:“用户名”,“密码”:“密码”]作为字典
变量错误:n错误?
request.HTTPBody=NSJSONSerialization.dataWithJSONObject(参数,选项:nil,错误:&err)
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
println(“响应:\(响应)”)}
task.resume()

因此,您想取消显示警告,或者想移动到
dataTaskWithRequest:completionHandler
?您好@Wain,我想纠正一下,如果正确的话,我更愿意取消显示警告。提前感谢。禁止对不推荐的方法发出警告不是一个好主意。正如警告所建议的那样,只需使用NSURLSession即可。正确的意思是升级到新的API,因为不推荐的API现在已过时,将来将不受支持并被删除抱歉,我不打算为您编写代码。阅读文档,自己尝试一下,如果仍然有问题,可以问一个特定的问题。感谢您的快速示例@Keller,我已经更改了您代码中的一些内容,现在它在没有警告的情况下工作。非常感谢。请告诉我keller,在得到webservice的响应后,我如何通过传递字典来推ViewController?向视图控制器的初始值设定项添加字典参数,或者如果您使用的是情节提要分段,请将字典保留在属性中,并将其设置为prepareForSegue。您还应该确保将视图控制器推送到主线程上。