如何在Swift中使用NSURLSessionDataTask

有人能帮我吗? 我无法find完成语法的一个很好的例子。

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(configuration: config)创build你的session

  2. session.dataTaskWithRequest返回一个NSURLSessionDataTask ,所以不需要把它包装在NSURLSessionDataTask() (也就是实例化一个新的NSURLSessionDataTask对象)。

  3. 完成处理程序是一个闭包,这里是如何创build特定的clousure:

     {(data : NSData!, response : NSURLResponse!, error : NSError!) in // your 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 eg run task.resume() 

如果在完成语法方面有问题,则可以在调用dataTaskWithRequest(..)之前创build完成函数,使其更清晰

 func handler (data: NSData!, response: NSURLResponse!, error: NSError!) { //handle what you need } session.dataTaskWithRequest(request, completionHandler: handler) 

你也可以简单地使用它:

 let url = "api url" let nsURL = NSURL let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) { (data, response, error) in // your condition on success and failure } task.resume() 

更新@ duemonk的代码Swift 3:

 do { var request = URLRequest(url: URL(string: "https://www.example.com/api/v1")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: {(data, response, error) in if error != nil { print(error!.localizedDescription) } else { print(response) } }) task.resume() } catch { // handle the error } 
 session.dataTaskWithRequest(request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in //code )} 

希望Xcode将被更新,以支持这些自动完成,导致语法是棘手的,Swift似乎并不支持声明返回types,但像这样使用时。