2017-01-10 121 views
1

我有一個下載類,根據給定的URL下載文件,然後調用一個完成,將文件的內容作爲NSData傳遞給它。Swift 3 - 下載JPEG圖像並保存到文件 - macOS

對於我正在使用它的項目,URL將是一個JPEG圖像。下載器完美地工作;我可以將結果用於NSImage,並將其顯示在Image View Controller中。

我想能夠將該NSData對象保存到文件。

經過相當長時間的研究Google,StackOverflow等互聯網,並嘗試了很多建議後,我無法保存文件。

下面是下載類的遊樂場和我試圖保存文件:

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

}) 
+0

我沒有遇到一個和嘗試過,但我有同樣的結果。沒有image.jpg文件被創建....編輯上面顯示的嘗試... – Johnno13

+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

+1

剛剛在操場上試過這個。仍然沒有創建image.jpg文件。 – Johnno13

+0

@ Johnno13操場是沙盒,你需要在一個真實的項目中測試它 –

+0

* facepalm * - data.write()在實際項目中沒有工作,但上面的方法沒有。 – Johnno13