问题描述
有人可以帮帮我吗?我找不到完成语法的好例子。
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)?)
谢谢!
不清楚你在问什么,但我注意到你在代码中有几个错误:
-
您应该使用
会话 >NSURLSession(配置:配置)
-
session.dataTaskWithRequest
返回NSURLSessionDataTask
,所以有没必要 将其包装在NSURLSessionDataTask()
中(也称为实例化新的NSURLSessionDataTask
对象)。 -
完成处理程序是一个闭包,下面是你如何创建特定的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:
You should create your
session
usingNSURLSession(configuration: config)
session.dataTaskWithRequest
returns aNSURLSessionDataTask
, so there's no need to wrap it insideNSURLSessionDataTask()
(a.k.a instantiating a newNSURLSessionDataTask
object).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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!