【问题标题】:Write Image To File in Directory将图像写入目录中的文件
【发布时间】:2016-11-25 16:50:42
【问题描述】:

在 Xcode 中将图像文件写入目录时出现错误。函数data.writeToFile 正在返回错误。这是我想要做的:

获取文件路径:

func getPath(fileName: String) -> String {
        let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let folder = "sampleDirectory"
        return documentURL.URLByAppendingPathComponent(folder).URLByAppendingPathComponent(fileName).path!
    }

保存图片

func saveImage(image: UIImage, path: String) -> Bool {
        let pngImageData = UIImagePNGRepresentation(image)
        do {
            let success = try pngImageData?.writeToFile(path, options: NSDataWritingOptions.init(rawValue: 0))
        } catch {
            print(error)
        }
        return false
    }

但是,有一个错误说:

NSPOSIXErrorDomain - code : 2

有谁知道问题出在哪里?

编辑 我在哪里调用代码:

let fileName = "first_image"
let imagePath = self.getPath(fileName)
let result = self.saveImage(processedImage, path: imagePath)

processedImage 是 UIImage 类型!

【问题讨论】:

  • iOS设备还是模拟器?
  • iOS 设备就是发生这种情况的地方。
  • 可以加saveImage(..)电话号码吗?
  • 我编辑了它。不确定它是否会有很大帮助。
  • 问题解决了,谢谢@LeoDabus。

标签: ios swift xcode nsfilemanager writetofile


【解决方案1】:

如果目录“sampleDirectory”不存在或不使用子目录,请尝试创建它。 您可以使用以下命令检查目录是否存在:

if !NSFileManager.defaultManager().fileExistsAtPath(path) { // create missing directories try! NSFileManager.defaultManager().createDirectoryAtPath(foo, withIntermediateDirectories: true, attributes: nil) }

您可能还想使用选项NSDataWritingOptions.DataWritingAtomic,它首先写入辅助文件,然后在没有错误的情况下交换文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2013-01-19
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多