一尘不染

如何在Swift中使用NSURLSessionDataTask

swift

有人能帮我吗?我找不到完整的语法示例。

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)?)

阅读 359

收藏
2020-07-07

共1个答案

一尘不染

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

  1. 您应该创建session使用NSURLSession(configuration: config)

  2. session.dataTaskWithRequest返回NSURLSessionDataTask,因此无需将其包装在内部NSURLSessionDataTask()(也称为实例化新NSURLSessionDataTask对象)。

  3. 完成处理程序是一个闭包,下面是创建该特定闭包的方法:

    {(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 e.g. run
task.resume()
2020-07-07