如何在Swift中使用NSURLSessionDataTask

如何在Swift中使用NSURLSessionDataTask

本文介绍了如何在Swift中使用NSURLSessionDataTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮帮我吗?我找不到完成语法的好例子。

  var url:NSURL = NSURL.URLWithString(https:/ /itunes.apple.com/search?term=\(searchTerm)&media=software)
var request:NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sessionWithConfiguration(config)

NSURLSessionDataTask(session.dataTaskWithRequest(request,completionHandler:((NSData!,NSURLResponse!,NSError!) - > Void)?)

谢谢!

解决方案

不清楚你在问什么,但我注意到你在代码中有几个错误:


  1. 您应该使用 NSURLSession(配置:配置) 会话 >


  2. session.dataTaskWithRequest 返回 NSURLSessionDataTask ,所以有没必要 将其包装在 NSURLSessionDataTask()中(也称为实例化新的 NSURLSessionDataTask 对象)。


  3. 完成处理程序是一个闭包,下面是你如何创建特定的clousure:

      { (数据:NSData!,响应:NSURLResponse!,错误:NSError!)in 

    //您的代码

    }


以下是更新后的代码:

  let url = NSURL(字符串:https://itunes.apple.com/search?term=\(searchTerm)&media=software)
let request = NSURLRequest (URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration:config)

let task = session.dataTaskWithRequest(request,completionHandler:{ (数据,响应,错误)在

//注意我可以省略数据类型,响应和错误

//你的代码

});

//执行任务所需的任何内容,例如run
task.resume()


Can someone help me? I can't find a good example for the completion syntax.

var url : NSURL = NSURL.URLWithString("https://itunes.apple.com/search?term=\(searchTerm)&media=software")
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sessionWithConfiguration(config)

NSURLSessionDataTask(session.dataTaskWithRequest(request, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?)

Thanks!

解决方案

It's unclear what you're asking, but I noticed that you have a couple of errors in the code:

  1. You should create your session using NSURLSession(configuration: config)

  2. session.dataTaskWithRequest returns a NSURLSessionDataTask, so there's no need to wrap it inside NSURLSessionDataTask() (a.k.a instantiating a new NSURLSessionDataTask object).

  3. The completion handler is a closure and here's how you create that particular clousure:

    {(data : NSData!, response : NSURLResponse!, error : NSError!) in
    
        // your code
    
    }
    

Here's the updated code:

let url = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
let request = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

    // notice that I can omit the types of data, response and error

    // your code

});

// do whatever you need with the task e.g. run
task.resume()

这篇关于如何在Swift中使用NSURLSessionDataTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:00