2017-01-10 5 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) 

}) 

遊び場コンソール全く何も表示しない:ここで

はダウンローダクラスの遊び場で、ファイルを保存するために私の試みです。誰もそれが動作しない理由を見つけることができますか?

注:対象はiOSではなくmacOSです。これは、アクセス許可の問題である可能性があり

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

私はその1に遭遇しなかったとことを試してみましたが、私は同じ結果を持っていました。 image.jpgファイルは作成されていません....上記を編集して試してみてください... – Johnno13

+0

私は私の投票結果を撤回しました。 –

答えて

0

:また、私は迅速noobのだ...

私はこれを試してみました。あなたが試すことがあります。

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

関連する問題