I've been learning swift rather quickly, and I'm trying to develop an OS X application that downloads images.

我已经能够将我正在查找的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)")
                }
            })
        }
    }
}

所以现在我把我的图像定义为"图像",但我没有掌握如何将这些文件保存到本地目录.

在这件事上如有任何帮助,我们将不胜感激!

Thanks,

tvick47

推荐答案

下面的代码将在applicationdocuments目录中的filename下写一个UIImage.jpg'

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)

Json相关问答推荐

将数组中的值作为键连接到另一个数组中的值(Jolt)

在Golang中从 struct 手动创建JSON对象

如何判断响应数组是否存在以及S是否有其他内容...?

无法使用Jolt变换在嵌套的JSON中提取值

嵌套 JSON 到 CSV(多级)

Serde JSON 反序列化枚举

如何在 onClick 事件处理程序中识别在同一 map 上绘制的多个多边形中的哪个(使用 react-leaflet)被单击?

为什么JsonConvert反序列化对象以int但不长失败

如何使用法语口音对数组进行 json_encode?

python,将Json写入文件

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

在 Apache Spark 中读取多行 JSON

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

在 Django 1.9 中,使用 JSONField(本机 postgres jsonb)的约定是什么?

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

嵌套 JSON:如何向对象添加(推送)新项目?

通过 JSON 发送 HTML 代码

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

我如何反序列化以杰克逊为单位的时间戳?

为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?