在 Swift 中載入/下載 URL 中的影像
在本文中,您將學習如何在 Swift 語言中從 URL 下載影像。
在 iOS 應用程式中,從影像 URL 下載影像是最常見的任務。Apple 為我們提供了一個原生庫來從任何 URL 下載任何資料。GitHub 上還有許多第三方庫可用於下載影像。
但在本教程中,我們不會使用任何第三方庫。我們將使用 Apple 自身提供的 URLSession 類。
什麼是 URLSession 類?
URLSession 是 Foundation 框架中的一個類,它提供了一個 API 用於透過網路連線從伺服器下載資料和上傳資料到伺服器。它使用 URL 來識別資源的位置,並且可以用於執行各種網路請求,包括 GET、POST、PUT 和 DELETE。
示例
以下是如何在 Swift 中使用 URLSession 發出 GET 請求的示例。
import UIKit let url = URL(string: "url_string")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let error = error { // handle error return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { // handle error return } if let data = data { // process data } } task.resume()
此程式碼建立一個表示 API 端點的 URL 物件,然後使用 URLSession 的 dataTask(with:) 方法建立一個 dataTask。dataTask 向伺服器傳送 GET 請求並檢索響應中的資料。當請求完成時,會呼叫 completion handler,它接收資料、響應和錯誤作為引數。
您可以使用 response 和 data 物件來處理伺服器的響應並根據需要處理資料。
要在 Swift 中從 URL 載入影像,您將使用相同的 URLSession 類向託管影像的伺服器傳送請求。然後,您將使用響應中的資料使用 UIImage 類建立影像。
以下是如何執行此操作的示例
演算法
步驟 1 - 建立一個類 ImageDownloader 和一個方法 downloadImage()。
步驟 2 - 檢查有效的 URL 物件,否則返回。
步驟 3 - 呼叫 URLSession 類的 dataTask() 方法。
步驟 4 - 在 dataTask() 方法中實現完成回撥。
步驟 5 - 在繼續下一步之前檢查錯誤。
步驟 6 - 使用 if-let 將接收到的資料轉換為 UIImage 物件。
示例
import UIKit class ImageDownloader { static func downloadImage(_ urlString: String, completion: ((_image: UIImage?, _ urlString: String?) -> ())?) { guard let url = URL(string: urlString) else { completion?(nil, urlString) return } URLSession.shared.dataTask(with: url) { (data, response,error) in if let error = error { print("error in downloading image: \(error)") completion?(nil, urlString) return } guard let httpResponse = response as? HTTPURLResponse,(200...299).contains(httpResponse.statusCode) else { completion?(nil, urlString) return } if let data = data, let image = UIImage(data: data) { completion?(image, urlString) return } completion?(nil, urlString) }.resume() } }
解釋
在上面的示例中,您可以看到在繼續執行之前驗證 URL 物件始終是一個可行的選擇。請求完成後,completion
handler 會提供資料、響應和錯誤。在從資料中獲取有效影像之前,請驗證是否收到了錯誤。
示例
import UIKit class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 16 imageView.layer.masksToBounds = true imageView.backgroundColor = UIColor(white: 0, alpha: 0.1)view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.widthAnchor.constraint(equalToConstant: 250).isActive = true imageView.heightAnchor.constraint(equalToConstant:250).isActive = true imageView.centerXAnchor.constraint(equalTo:view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true ImageDownloader.downloadImage("https://picsum.photos/300") { image, urlString in if let imageObject = image { // performing UI operation on main thread DispatchQueue.main.async { imageView.image = imageObject } } } } }
請注意,此程式碼使用 URLSession 的 dataTask 方法非同步執行請求。這意味著影像將在後臺載入,並且主執行緒不會被阻塞。這對於確保您的應用程式在載入影像時保持響應非常重要。
輸出
結論
請注意,URLSession 還提供其他用於執行網路請求的方法,例如用於將資料上傳到伺服器的 uploadTask 和用於從伺服器下載資料的 downloadTask。您可以根據需要使用這些方法。