使用 URLSession 从 url 下载 jpg 图像
Downloading jpg image from url with URLSession
我正在尝试从 swift 中的 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()
}
第二次打印的Content-type是image/jpeg,错误打印是nil。
我的下载代码有问题吗?
一般来说,在 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
16=]
首先将Kingfisher导入为-
pod 'Kingfisher'
然后将其导入您的 class 为 -
import Kingfisher
之后添加一个临时的 UIImageView
let imgView = UIImageView()
imgView.kf.setImage(with: yourImageURL)
if let finalImage = imgView.image {
// finalImage is your image
}
我正在尝试从 swift 中的 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()
}
第二次打印的Content-type是image/jpeg,错误打印是nil。
我的下载代码有问题吗?
一般来说,在 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
16=]
首先将Kingfisher导入为-
pod 'Kingfisher'
然后将其导入您的 class 为 -
import Kingfisher
之后添加一个临时的 UIImageView
let imgView = UIImageView()
imgView.kf.setImage(with: yourImageURL)
if let finalImage = imgView.image {
// finalImage is your image
}