json Swift - 将图像从 URL 写入本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26171901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - Write Image from URL to Local File
提问by Tyler
I've been learning swift rather quickly, and I'm trying to develop an OS X application that downloads images.
我一直在快速学习,并且正在尝试开发一个下载图像的 OS X 应用程序。
I've been able to parse the JSON I'm looking for into an array of URLs as follows:
我已经能够将我正在寻找的 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)")
}
})
}
}
}
So at this point I have my images defined as "image", but what I'm failing to grasp here is how to save these files to my local directory.
所以此时我将我的图像定义为“图像”,但我在这里未能掌握的是如何将这些文件保存到我的本地目录。
Any help on this matter would be greatly appreciated!
对此事的任何帮助将不胜感激!
Thanks,
谢谢,
tvick47
tick47
采纳答案by kurtn718
The following code would write a UIImagein the Application Documents directory under the filename 'filename.jpg'
以下代码将UIImage在文件名“filename.jpg”下的 Application Documents 目录中写入
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)
回答by JPetric
In Swift 3:
在Swift 3 中:
Write
写
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 { }
Read
读
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)
}
回答by Mario Hendricks
In swift 2.0, stringByAppendingPathComponent is unavailable, so the answer changes a bit. Here is what I've done to write a UIImage out to disk.
在 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)
}
}
回答by Ted Breeden
UIImagePNGRepresentaton() function had been deprecated. try image.pngData()
UIImagePNGRepresentaton() 函数已被弃用。试试 image.pngData()
回答by hamayun zeb
@IBAction func savePhoto(_ sender: Any) {
let imageData = UIImagePNGRepresentation(myImg.image!)
let compresedImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compresedImage!, nil, nil, nil)
let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default)
alert.addAction(okAction)
self.present(alert, animated: true)
}
}
回答by Nic Wanavit
Update for swift 5
Swift 5 的更新
just change filename.pngto something else
只是换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
}
}

