ios 如何在 Swift 中使用 NSURLSessionDataTask
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24040893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use NSURLSessionDataTask in Swift
提问by DookieMan
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)?)
回答by akashivskyy
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 }
你应该创建你的
session
使用NSURLSession(configuration: config)
session.dataTaskWithRequest
返回 aNSURLSessionDataTask
,因此无需将其包装在里面NSURLSessionDataTask()
(也就是实例化一个新NSURLSessionDataTask
对象)。完成处理程序是一个闭包,以下是您创建该特定闭包的方法:
{(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()
回答by eXhausted
If you have problems with completion syntax, you can create function for completion before calling dataTaskWithRequest(..) to make it clearer
如果您对完成语法有问题,您可以在调用 dataTaskWithRequest(..) 之前创建完成功能以使其更清晰
func handler (data: NSData!, response: NSURLResponse!, error: NSError!) {
//handle what you need
}
session.dataTaskWithRequest(request, completionHandler: handler)
回答by Rachit
You can also use it simply by :-
您也可以简单地通过以下方式使用它:-
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()
回答by Francis Jervis
Updated @duemonk's code for Swift 3:
为 Swift 3 更新了 @duemonk 的代码:
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
}
回答by Oktay
Swift 4.2
斯威夫特 4.2
let url = URL(string: "http://url.com")!
let request = URLRequest(url: url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
print(String(data: data!, encoding: .utf8)!)
});
task.resume()
回答by malhal
session.dataTaskWithRequest(request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in
//code
)}
Hopefully Xcode will be updated to support auto-complete for these, cause the syntax is kind of tricky, and Swift doesn't appear to support declaring the return type yet when used like this.
希望 Xcode 将更新以支持这些自动完成,因为语法有点棘手,而且当像这样使用时,Swift 似乎还不支持声明返回类型。