【问题标题】:iOS Write Data to file, FILE DOES NOT EXISTiOS 将数据写入文件,文件不存在
【发布时间】:2018-10-21 16:40:32
【问题描述】:

我正在尝试将图像的数据写入缓存目录中,如下所示:

let imageData = UIImageJPEGRepresentation(image, 1.0) else { fatalError("Impossible to read the image") }
try! imageData.write(to: cachedImageURL, options: .atomic)
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))

image 是一个工作的 UIImage。 Print 语句总是返回 False。该文件永远不会被写入,并且由于“try!

而引发任何异常

有什么想法吗?

打印缓存的ImageURL,看起来是这样的

file:///var/mobile/Containers/Data/Application/7B6B72C8-E794-4474-A658-48B66AEA31EC/Library/Caches/79d0e60e-5961-4538-bd9f-28187f4e26d0.jpg

【问题讨论】:

    标签: ios image caching nsdata writetofile


    【解决方案1】:

    刚刚想通了。问题出在我的印刷品上

    print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
    

    应该是 cachedImageURL.path 而不是 cachedImageURL.absoluteString

    print(fileManager.fileExists(atPath: cachedImageURL.path))
    

    【讨论】:

      【解决方案2】:

      您可以尝试以下代码将图像保存到缓存目录

      *注意:如果您要保存多个图像,请为所有图像命名

      let fileManager = FileManager.default
      let imageName = "image.jpg" //Need to change if more images want to save
      
      do {
          let cachesDirectory = try fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
          let fileURL = cachesDirectory.appendingPathComponent(imageName)
          let image = your image //Give your image here
          if let imageData = UIImageJPEGRepresentation(image, 1.0) {
              try imageData.write(to: fileURL)
              print("Image Saved")
          }
      } catch {
             print(error.localizedDescription)
      }
      

      【讨论】:

      • 我运行相同的代码,我能够将图像存储在缓存目录中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多