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

Json Swift-将图像从URL写入本地文件,json,macos,cocoa,swift,osx-yosemite,Json,Macos,Cocoa,Swift,Osx Yosemite,我学习swift的速度相当快,我正在尝试开发一个可以下载图像的OSX应用程序 我已经能够将我正在寻找的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

我学习swift的速度相当快,我正在尝试开发一个可以下载图像的OSX应用程序

我已经能够将我正在寻找的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

以下代码将在文件名“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)

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

在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)
}
UIImagePNGRepresentaton()函数已被弃用。尝试image.pngData()

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

func writeImageToDocs(图像:UIImage){
将documentsPath=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)[0]设为字符串
让destinationPath=URL(fileURLWithPath:documentsPath)。appendingPathComponent(“filename.png”)
debugPrint(“目标路径为”,destinationPath)
做{
尝试image.pngData()?.write(到:destinationPath)
}抓住{
debugPrint(“写入文件错误”,错误)
}
}
func readImageFromDocs()->UIImage{
将documentsPath=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)[0]设为字符串
让filePath=URL(fileURLWithPath:documentsPath).appendingPathComponent(“filename.png”).path
如果FileManager.default.fileExists(atPath:filePath){
返回UIImage(内容文件:文件路径)
}否则{
归零
}
}

感谢您的回复!但是,每当我尝试使用该代码构建时,我都会收到错误:
使用未解析标识符“UIImageJPEGRepresentation”
该函数存在于iOS上。下面是如何使用Objective-C中的Mac API来实现这一点。将发布Swift版本,感谢您的更新!虽然我确实理解得更深入一些,但swift版本确实能帮我解决问题。谢谢String没有<代码> String ByEndPurnPultCys1/<代码> -请考虑添加关于图像DeleTeNi AM的信息,试图使用UIIVIEPNGRePress()函数,但XCODEL由于某种原因无法识别它。我正在使用Swift 4.2.try pngData()PNG已更改
@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)
    }   
}