json - Swift - 将图像从 URL 写入本地文件

标签 json macos cocoa swift osx-yosemite

我学得很快,我正在尝试开发一个下载图像的 OS X 应用程序。

我已经能够将我正在寻找的 JSON 解析为 URL 数组,如下所示:

func didReceiveAPIResults(results: NSArray) {
    println(results)
    for link in results {
        let stringLink = link as String
        //Check to make sure that the string is actually pointing to a file
        if stringLink.lowercaseString.rangeOfString(".jpg") != nil {2

            //Convert string to url
            var imgURL: NSURL = NSURL(string: stringLink)!

            //Download an NSData representation of the image from URL
            var request: NSURLRequest = NSURLRequest(URL: imgURL)

            var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)!
            //Make request to download URL
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                if !(error? != nil) {
                    //set image to requested resource
                    var image = NSImage(data: data)

                } else {
                    //If request fails...
                    println("error: \(error.localizedDescription)")
                }
            })
        }
    }
}

所以此时我将我的图像定义为“图像”,但我在这里未能掌握的是如何将这些文件保存到我的本地目录。

任何关于此事的帮助将不胜感激!

谢谢,

tvick47

最佳答案

Swift 3 中:

do {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = documentsURL.appendingPathComponent("\(fileName).png")
    if let pngImageData = UIImagePNGRepresentation(image) {
    try pngImageData.write(to: fileURL, options: .atomic)
    }
} catch { }

阅读

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent("\(fileName).png").path
if FileManager.default.fileExists(atPath: filePath) {
    return UIImage(contentsOfFile: filePath)
}

关于json - Swift - 将图像从 URL 写入本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171901/

相关文章:

cocoa - 如何以编程方式从 runModal() 中关闭 NSAlert?

xcode - cocoa -Applescript : Placing a GUI in an applescript

javascript - 将 JavaScript 变量传递给 ruby​​-on-rails Controller

javascript - JSON 对象流

ios - Swift 套接字

java 6 在 mac 10.5.8 上使用 SoyLatte

objective-c - bundleAtPath 给了我错误的路径

javascript - 如何动态调用Json对象?

javascript - 如何使用 javascript 获取嵌套 Json 对象的名称

swift - 如何在 NSApplicationDelegate 上加载 NSViewController