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

问题描述 投票:28回答:4

我一直在快速学习,我正在尝试开发一个下载图像的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

json macos cocoa swift osx-yosemite
4个回答
26
投票

以下代码将在Application Documents目录中以文件名'filename.jpg'编写UIImage

var image = ....  // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)

38
投票

在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)
}

17
投票

在swift 2.0中,stringByAppendingPathComponent不可用,所以答案会有所改变。以下是我将UIImage写入磁盘所做的工作。

documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
if let image = UIImage(data: someNSDataRepresentingAnImage) {
    let fileURL = documentsURL.URLByAppendingPathComponent(fileName+".png")
    if let pngImageData = UIImagePNGRepresentation(image) {
        pngImageData.writeToURL(fileURL, atomically: false)
    }
}

1
投票

UIImagePNGRepresentaton()函数已被弃用。试试image.pngData()

© www.soinside.com 2019 - 2024. All rights reserved.