将 NSURLConnection 更改为 NSURLSession 后加载图像很慢
Loading images is slow after changing NSURLConnection to NSURLSession
我在 iOS 8 中有一个代码用于加载我的图像,速度非常快。
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
self.image = UIImage(data: data!)
}
}
然后 iOS 9 出来了,我为此苦苦挣扎
let session = NSURLSession.sharedSession()
let urlString = urlString
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.image = UIImage(data: data!)
}
dataTask.resume()
图片加载速度很慢。
在 dataTaskWithRequest
闭包中,您必须在主线程上更新图像。这样做:
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.image = UIImage(data: data!)
}
}
我在 iOS 8 中有一个代码用于加载我的图像,速度非常快。
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
self.image = UIImage(data: data!)
}
}
然后 iOS 9 出来了,我为此苦苦挣扎
let session = NSURLSession.sharedSession()
let urlString = urlString
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.image = UIImage(data: data!)
}
dataTask.resume()
图片加载速度很慢。
在 dataTaskWithRequest
闭包中,您必须在主线程上更新图像。这样做:
let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.image = UIImage(data: data!)
}
}