Swift 3 - 下载JPEG图像并保存到文件 - macOS

时间:2017-01-10 06:06:18

标签: swift3 xcode8 macos-sierra

我有一个下载程序类,它根据给定的URL下载文件,然后调用完成,将文件的内容作为NSData传递给它。

对于我正在使用此项目的项目,URL将是JPEG图像。下载器完美运行;我可以将结果用于NSImage并在图像视图控制器中显示它。

我希望能够将该NSData对象保存到文件中。

经过一段时间研究Google,StackOverflow等互联网并尝试了很多建议后,我无法保存文件。

这是Downloader类的一个操场,我尝试保存文件:

//: 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)

})

游乐场控制台根本没有显示任何内容。谁能发现它为什么不起作用?

注意:目标是 macOS ,而不是iOS。而且,我是一个快速的菜鸟......

我试过这个:

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!")
        }
    }

})

1 个答案:

答案 0 :(得分:0)

这可能是一个许可问题。你可以尝试:

let picturesDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let imageUrl = picturesDirectory.appendingPathComponent("image.jpg", isDirectory: false)
try? data.write(to: imageUrl)

它对我有用: enter image description here