Swift 2 - 防止加载大gif文件卡住
我有2MB的GIF文件,但是当我使用celluar和我的高速结束时,我有15kb/s,我必须等待一定的时间才能继续使用应用程序..Swift 2 - 防止加载大gif文件卡住
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
getGif()
}
func getGif(){
dispatch_async(dispatch_get_main_queue(), {
do{
if let json = try NSJSONSerialization.JSONObjectWithData(NSData(contentsOfURL: NSURL(string: "http://google.bg/gif.php")!)!, options: .MutableContainers) as? NSArray{
self.gifUrl = json[0]["url"] as! String
self.theGif.image = UIImage.gifWithURL(self.gifUrl)
}
}catch{}
})
}
调度不工作...
如何继续使用应用程序,而图像加载?
获取关闭主线程进行下载,然后拿到上主线程交谈的接口:
func getGif(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)), {
do{
if let json = try NSJSONSerialization.JSONObjectWithData(NSData(contentsOfURL: NSURL(string: "http://google.bg/gif.php")!)!, options: .MutableContainers) as? NSArray{
dispatch_async(dispatch_get_main_queue(), {
self.gifUrl = json[0]["url"] as! String
self.theGif.image = UIImage.gifWithURL(self.gifUrl)
}
}
}catch{}
})
}
但是,正如您所知道的那样,使用NSURLSession进行正确的下载会更好。
extension UIImage {
public class func gifWithURL(gifUrl:String, completion: (data: NSData)->()) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(NSURL(string: gifUrl)!) { (data, response, error) in
if error == nil {
dispatch_async(dispatch_get_main_queue(), {
completion(data: data!)
})
}
}
task.resume()
}
}
这是一个正确的方法,但现在我收到数据时无法显示gif:直接使用https://github.com/bahlo/SwiftGif –
我没有看到你在哪里采用了上述代码github项目。 – matt
它显示了很多延迟,但在完成处理程序我收到打印(“完成”)可能10-20秒后我收到数据 –
使用NSURLSession下载您的数据。 Starter tip here:http://*.com/a/35358750/2227743 – Moritz
与Eric同意,不要使用'NSData'的'contentsOfURL',它会阻塞主线程。 – JAL