2017-08-17 67 views

回答

1

這是我下載圖像功能,你只需要下載網址:

let imageCache = NSCache<AnyObject, AnyObject>() 

func downloadImageFromURL(string: String) -> UIImage { 

    if let cachedImage = imageCache.object(forKey: string as AnyObject) as? UIImage { 

     return cachedImage 

    } else { 

     let data = NSData(contentsOf: URL(string: string)!) 
     return UIImage(data: data! as Data)! 

    } 

} 

您只需撥打:let image = downloadImageFromURL("yourURL")

編輯

這是直接下載圖片到版我以前用過的imageView;這是一個不同的方法,也許它會加載速度更快:

let imageCache = NSCache<AnyObject, AnyObject>() 

extension UIImageView { 


func downloadImage(from imgURL: String!) { 

    self.image = nil 

    // Check if there's an image in the cache 

    if let cachedImage = imageCache.object(forKey: imgURL as AnyObject) as? UIImage { 
     self.image = cachedImage 
     return 
    } 

    // Otherwise, download image from Firebase via URL-string 

    let url = URLRequest(url: URL(string: imgURL)!) 

    let task = URLSession.shared.dataTask(with: url) { 
     (data, response, error) in 

     if error != nil { 
      print(error!) 
      return 
     } 

     DispatchQueue.main.async { 
      if let image = UIImage(data: data!) { 
       imageCache.setObject(image, forKey: imgURL as AnyObject) 
      } 
      self.image = UIImage(data: data!) 
     } 

    } 

    task.resume() 
} 
} 
+0

謝謝,但它確實需要花費大量的時間來下載,是不是有什麼更快的方式? –

+1

這取決於您的互聯網連接;)不,這是推薦的下載數據的方式。但是,如果有人連接不好,您可以做什麼,以及我所做的是上傳壓縮版本的圖像。上傳時,只需說:let data = UIImageJPEGRepresentation(yourImage,0.7);上傳壓縮版本的圖像,並認真地說,沒有太大的區別。 –

+0

好的,謝謝你的回答! –

相關問題