【问题标题】:Swift - Write Image from URL to Local FileSwift - 将图像从 URL 写入本地文件
【发布时间】:2014-11-28 02:18:23
【问题描述】:

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

【问题讨论】:

    标签: json macos cocoa swift osx-yosemite


    【解决方案1】:

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

    【讨论】:

    • 很好的答案 - 请考虑添加有关图像删除的信息
    • 我正在尝试使用 UIImagePNGRepresentation() 函数,但 Xcode 由于某种原因无法识别它。我正在使用 Swift 4.2。
    • 尝试 pngData() 更改 PNG
    【解决方案2】:

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

    【讨论】:

    • 感谢您的回复!但是,每当我尝试使用该代码进行构建时,都会收到错误消息:Use of unresolved identifier 'UIImageJPEGRepresentation'
    • 该功能在iOS上存在。以下是在 Objective-C 中使用 Mac API 的方法。将发布 Swift 版本stackoverflow.com/questions/3038820/…
    • 感谢您的更新!虽然我确实理解得更深一点,但快速版本真的会帮助我。谢谢!
    • 字符串没有stringByAppendingPathComponent
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:
        @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)
            }   
        }
        

        【讨论】:

          【解决方案6】:

          swift 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
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-08-15
            • 1970-01-01
            • 2017-06-22
            • 1970-01-01
            • 2014-09-18
            • 2018-02-23
            • 2011-12-06
            • 1970-01-01
            相关资源
            最近更新 更多