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