NSFileManager 创建文件失败
NSFileManager Failing on create file
这是我保存图像的函数。
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)
当我调用创建文件时每次都是 returns false 并且照片没有保存。
编辑:问题是第二行需要是 documentDirectory 而不是 picturesDirectory。如下图:
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0]
iOS 沙盒中的应用程序 运行。您无法写入图片文件夹。
如果您想将图片添加到用户的照片库中,请使用 PHPhotoLibrary
或仅 UIImageWriteToSavedPhotosAlbum
。
如果您只想将图像保存在您自己的应用程序中,请将文件存储在 Documents 文件夹中。
仅供参考 - 在 iOS 中使用 NSSearchPathForDirectoriesInDomains
时,唯一有用的目录是:
- 图书馆目录
- 文档目录
- 缓存目录
- applicationSupportDirectory
所有其他的只在 macOS 中有用。
这是我保存图像的函数。
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)
当我调用创建文件时每次都是 returns false 并且照片没有保存。
编辑:问题是第二行需要是 documentDirectory 而不是 picturesDirectory。如下图:
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0]
iOS 沙盒中的应用程序 运行。您无法写入图片文件夹。
如果您想将图片添加到用户的照片库中,请使用 PHPhotoLibrary
或仅 UIImageWriteToSavedPhotosAlbum
。
如果您只想将图像保存在您自己的应用程序中,请将文件存储在 Documents 文件夹中。
仅供参考 - 在 iOS 中使用 NSSearchPathForDirectoriesInDomains
时,唯一有用的目录是:
- 图书馆目录
- 文档目录
- 缓存目录
- applicationSupportDirectory
所有其他的只在 macOS 中有用。