簡體   English   中英

使用 URLSession 從 url 下載 jpg 圖像

[英]Downloading jpg image from url with URLSession

我正在嘗試快速從 url 下載圖像。 這是我嘗試下載的圖像url ,我希望它將它下載到應用程序文檔目錄中的 On my iPhone > testExampleApplication,但是當我單擊該按鈕時,沒有下載任何內容。 這是我的代碼:

Button("Download logo image") {
      let imageUrlStr = "https://media.wired.com/photos/5f2d7c2191d87e6680b80936/16:9/w_2400,h_1350,c_limit/Science_climatedesk_453801484.jpg".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
      let task = URLSession.shared.dataTask(with: URLRequest(url: URL(string: imageUrlStr)!), completionHandler: {(data, response, error) -> Void in
        print("download details 1: \(data)")
        print("download details 2: \(response)")
        print("download details 3: \(error)")
      })
      // Start the download.
      task.resume()
}

第二次打印的內容類型是圖像/jpeg,錯誤打印是零。

我在下載代碼中做錯了什么嗎?

通常,在ObservableObject而不是View本身中執行這樣的異步任務是個好主意。

您已經在進行下載——您現在需要做的就是保存數據:

class Downloader : ObservableObject {
    func downloadImage() {
        let imageUrlStr = "https://media.wired.com/photos/5f2d7c2191d87e6680b80936/16:9/w_2400,h_1350,c_limit/Science_climatedesk_453801484.jpg".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
              let task = URLSession.shared.dataTask(with: URLRequest(url: URL(string: imageUrlStr)!), completionHandler: {(data, response, error) -> Void in
                
                  guard let data = data else {
                      print("No image data")
                      return
                  }
                  
                  do {
                      try data.write(to: self.getDocumentsDirectory().appendingPathComponent("image.jpg"))
                      print("Image saved to: ",self.getDocumentsDirectory())
                  } catch {
                      print(error)
                  }
                  
              })
              // Start the download.
              task.resume()
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
}

struct ContentView : View {
    @StateObject private var downloader = Downloader()
    
    var body : some View {
        Button("Download") {
            downloader.downloadImage()
        }
    }
}

如果您在模擬器中運行它,您可以看到輸出到控制台的目錄位置。 如果您在 Finder 中打開它,您會看到您的圖像已保存在那里。

請注意,要查看 Files 應用程序中的目錄和文件,您需要確保已在Info.plist中將UIFileSharingEnabled設置為YES

首先導入翠鳥為-

pod 'Kingfisher'

然后將其導入您的課程中 -

import Kingfisher

之后添加一個臨時的 UIImageView

let imgView = UIImageView()
imgView.kf.setImage(with: yourImageURL)

if let finalImage = imgView.image {
    // finalImage is your image
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM