Swift 3 - 下载 JPEG 图像并保存到文件 - macOS
Swift 3 - Download JPEG image and save to file - macOS
我有一个下载器 class,它根据给定的 URL 下载一个文件,然后调用完成将文件内容作为 NSData 传递给它。
对于我在其中使用它的项目,URL 将是 JPEG 图像。下载器完美运行;我可以将结果用于 NSImage 并将其显示在图像视图控制器中。
我希望能够将该 NSData 对象保存到文件中。
在 Google、Whosebug 等网上搜索了很长一段时间并尝试了很多建议后,我无法保存文件。
这是下载器的游乐场 class 和我保存文件的尝试:
//: Playground - noun: a place where people can play
import Cocoa
class NetworkService
{
lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = URLSession(configuration: self.configuration)
let url: NSURL
init(url: NSURL)
{
self.url = url
}
func downloadImage(completion: @escaping ((NSData) -> Void))
{
let request = NSURLRequest(url: self.url as URL)
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error == nil {
if let httpResponse = response as? HTTPURLResponse {
switch (httpResponse.statusCode) {
case 200:
if let data = data {
completion(data as NSData)
}
default:
print(httpResponse.statusCode)
}
}
} else {
print("Error download data: \(error?.localizedDescription)")
}
}
dataTask.resume()
}
}
let IMAGE_URL = NSURL(string: "https://www.bing.com/az/hprichbg/rb/RossFountain_EN-AU11490955168_1920x1080.jpg")
let networkService = NetworkService(url: IMAGE_URL!)
networkService.downloadImage(completion: { (data) in
data.write(to: URL(string: "file://~/Pictures/image.jpg")!, atomically: false)
})
playground 控制台什么也没有显示。谁能看出它为什么不起作用?
注意:目标是 macOS,而不是 iOS。另外,我是一个 swift 菜鸟...
我试过这个:
networkService.downloadImage(completion: { (imageData) in
let imageAsNSImage = NSImage(data: imageData as Data)
if let bits = imageAsNSImage?.representations.first as? NSBitmapImageRep {
let outputData = bits.representation(using: .JPEG, properties: [:])
do {
try outputData?.write(to: URL(string: "file://~/Pictures/myImage.jpg")!)
} catch {
print("ERROR!")
}
}
})
可能是权限问题。你可以试试:
let picturesDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let imageUrl = picturesDirectory.appendingPathComponent("image.jpg", isDirectory: false)
try? data.write(to: imageUrl)
它对我有用:
我有一个下载器 class,它根据给定的 URL 下载一个文件,然后调用完成将文件内容作为 NSData 传递给它。
对于我在其中使用它的项目,URL 将是 JPEG 图像。下载器完美运行;我可以将结果用于 NSImage 并将其显示在图像视图控制器中。
我希望能够将该 NSData 对象保存到文件中。
在 Google、Whosebug 等网上搜索了很长一段时间并尝试了很多建议后,我无法保存文件。
这是下载器的游乐场 class 和我保存文件的尝试:
//: Playground - noun: a place where people can play
import Cocoa
class NetworkService
{
lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = URLSession(configuration: self.configuration)
let url: NSURL
init(url: NSURL)
{
self.url = url
}
func downloadImage(completion: @escaping ((NSData) -> Void))
{
let request = NSURLRequest(url: self.url as URL)
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error == nil {
if let httpResponse = response as? HTTPURLResponse {
switch (httpResponse.statusCode) {
case 200:
if let data = data {
completion(data as NSData)
}
default:
print(httpResponse.statusCode)
}
}
} else {
print("Error download data: \(error?.localizedDescription)")
}
}
dataTask.resume()
}
}
let IMAGE_URL = NSURL(string: "https://www.bing.com/az/hprichbg/rb/RossFountain_EN-AU11490955168_1920x1080.jpg")
let networkService = NetworkService(url: IMAGE_URL!)
networkService.downloadImage(completion: { (data) in
data.write(to: URL(string: "file://~/Pictures/image.jpg")!, atomically: false)
})
playground 控制台什么也没有显示。谁能看出它为什么不起作用?
注意:目标是 macOS,而不是 iOS。另外,我是一个 swift 菜鸟...
我试过这个:
networkService.downloadImage(completion: { (imageData) in
let imageAsNSImage = NSImage(data: imageData as Data)
if let bits = imageAsNSImage?.representations.first as? NSBitmapImageRep {
let outputData = bits.representation(using: .JPEG, properties: [:])
do {
try outputData?.write(to: URL(string: "file://~/Pictures/myImage.jpg")!)
} catch {
print("ERROR!")
}
}
})
可能是权限问题。你可以试试:
let picturesDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let imageUrl = picturesDirectory.appendingPathComponent("image.jpg", isDirectory: false)
try? data.write(to: imageUrl)
它对我有用: