2016-03-08 63 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秒後我收到數據 –