【问题标题】:Downloading jpg image from url with URLSession使用 URLSession 从 url 下载 jpg 图像
【发布时间】:2021-12-01 14:09:00
【问题描述】:

我正在尝试从 swift 中的 url 下载图像。这是我正在尝试下载的图像url,我希望它能够将其下载到应用程序文档目录中的我的 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()
}

第二次打印的Content-type是image/jpeg,错误打印是nil。

我的下载代码有问题吗?

【问题讨论】:

  • 您的标题是png,然后您引用的是jpg 图像。但是,这可能无论如何都无关紧要,因为与更重要的问题相比,图像类型不太重要:您期望发生什么?看起来您当前的代码正在运行。您是否尝试将其保存到应用程序的文档目录中?还是去照片库?
  • 嗨,谢谢你,我刚刚更新了标题。因此,对于您的问题,我正在尝试将其保存在应用程序的文档目录中,而不是照片库中。我实际上会继续并将其放在我的问题中。
  • 您可以使用 Kingfisher 从 url 获取图像。
  • @Imran0001 你能提供一个关于如何使用这个库下载图像的答案或示例吗?
  • @Amy,我只是在写。

标签: ios swift swiftui urlsession


【解决方案1】:

一般来说,在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 中打开它,你会看到你的图片已经保存在那里。

请注意,要在“文件”应用中查看目录和文件,您需要确保在 Info.plist 中将 UIFileSharingEnabled 设置为 YES

【讨论】:

    【解决方案2】:

    首先导入Kingfisher as-

    pod 'Kingfisher'
    

    然后在你的类中导入它 -

    import Kingfisher
    

    之后添加一个临时的 UIImageView

    let imgView = UIImageView()
    imgView.kf.setImage(with: yourImageURL)
    
    if let finalImage = imgView.image {
        // finalImage is your image
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2021-10-22
      相关资源
      最近更新 更多