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

时间:2014-10-03 01:05:53

标签: 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

6 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:26)

以下代码会在文件名&#39; filename.jpg&#39;

下的Application Documents目录中写一个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)

答案 2 :(得分: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)
    }
}

答案 3 :(得分:1)

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

答案 4 :(得分:0)

protected function grid()  
{
    ...
    $grid->column('com_num', __('com_num'))->display(function (){
        return '/admin/com/search/'.$this->sn;
    })->link();
    ...
}

答案 5 :(得分:0)

更新为快速5

只需将filename.png更改为其他内容

func writeImageToDocs(image:UIImage){
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String

    let destinationPath = URL(fileURLWithPath: documentsPath).appendingPathComponent("filename.png")

    debugPrint("destination path is",destinationPath)

    do {
        try image.pngData()?.write(to: destinationPath)
    } catch {
        debugPrint("writing file error", error)
    }
}

func readImageFromDocs()->UIImage?{
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String

    let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent("filename.png").path
    if FileManager.default.fileExists(atPath: filePath) {
        return UIImage(contentsOfFile: filePath)
    } else {
        return nil
    }
}
相关问题