use*_*331 2 nsurlconnection ios nsurlsession swift
我NSURLSession在我的应用程序中使用如下:
func wsQAshowTag(tag: Int, completion: ([AnyObject]! -> Void)) {
let requestString = NSString(format: “URL”, tag) as String
let url: NSURL! = NSURL(string: requestString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
data, response, error in
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
completion(result)
}
catch {
completion(nil)
}
})
task.resume()
}
Run Code Online (Sandbox Code Playgroud)
这可以按预期工作,但我发现它非常慢,当我使用时NSURLConnection我发现它非常快(这是使用相同的URL)NSURLSession如果NSURLConnection非常快,怎么来非常慢?还有加速NSURLSession吗?
这是我如何称呼它:
self.wsQAshowTag(Int(barcode)!, completion: { wsQAshowTagArray in
//Code Here
})
Run Code Online (Sandbox Code Playgroud)
您需要将UI更新发送到主队列.如果更新它而不将其发送到主队列,则更新数据可能需要很长时间.
您还需要进行换行,completion(result)因为我们正在解析JSON.
代码抓取存储的完成处理程序并在主线程上调用它.
func wsQAshowTag(tag: Int, completion: ([AnyObject]! -> Void)) {
let requestString = NSString(format: "URL", tag) as String
let url: NSURL! = NSURL(string: requestString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
data, response, error in
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
dispatch_async(dispatch_get_main_queue()) {
completion(result)
}
} catch {
dispatch_async(dispatch_get_main_queue()) {
completion(nil)
}
print("error serializing JSON: \(error)")
}
})
task.resume()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3705 次 |
| 最近记录: |