这是我保存图像的函数。
static func getDirectoryPath() -> String {
let path = (NSSearchPathForDirectoriesInDomains(.picturesDirectory, .userDomainMask, true))[0]
return path
}
static func savePhoto(with path: String, image: UIImage) {
let fM = FileManager.default
let path = getDirectoryPath() + path
let data = UIImageJPEGRepresentation(image, 0.5)
let success = fM.createFile(atPath: path, contents: data, attributes: nil)
print("File creation was \(success)")
}
然后我这样调用它
let path = "/SpotCheck_\(spot.name)_Photo\(indx).jpg"
PhotoManager.savePhoto(with: path, image: photo)
当我调用创建文件时每次都返回 false 并且照片没有保存。
编辑:问题是第二行需要是 documentDirectory 而不是 picturesDirectory。如下图:
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0]
最佳答案
iOS 应用在沙盒中运行。您无法写入图片文件夹。
如果您想将图片添加到用户的照片库中,请使用 PHPhotoLibrary
或仅使用 UIImageWriteToSavedPhotosAlbum
。
如果您只想将图像保存在您自己的应用程序中,请将文件存储在 Documents 文件夹中。
仅供引用 - 在 iOS 中使用 NSSearchPathForDirectoriesInDomains
时,唯一有用的目录是:
- 图书馆目录
- 文档目录
- 缓存目录
- 应用程序支持目录
所有其他的仅在 macOS 中有用。
关于ios - NSFileManager 创建文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46146732/