2016-03-08 65 views
-3

我有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{} 
    }) 
} 

调度不工作...

如何继续使用应用程序,而图像加载?

+1

使用NSURLSession下载您的数据。 Starter tip here:http://stackoverflow.com/a/35358750/2227743 – Moritz

+0

与Eric同意,不要使用'NSData'的'contentsOfURL',它会阻塞主线程。 – JAL

回答

2

获取关闭主线程进行下载,然后拿到主线程交谈的接口:

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进行正确的下载会更好。

0

您在主队列上使用dispatch_async,以便在主线程上执行代码。

尝试用dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))代替。

此外还有一些很好的库,可以隐藏像Async这样的GCD复杂性。如果你需要在GCD更多信息本身随便看看Apple Doc

1
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() 
    } 
} 
+0

这是一个正确的方法,但现在我收到数据时无法显示gif:直接使用https://github.com/bahlo/SwiftGif –

+0

我没有看到你在哪里采用了上述代码github项目。 – matt

+0

它显示了很多延迟,但在完成处理程序我收到打印(“完成”)可能10-20秒后我收到数据 –