以下是保存图像的功能。
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)
当我调用create file时,每次都返回false并且不保存照片。
编辑:问题是第二行需要documentDirectory而不是picturesDirectory。如下图所示:
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0]
答案 0 :(得分:5)
iOS应用在沙盒中运行。您无法写入图片文件夹。
如果您想将图片添加到用户的照片库,请使用PHPhotoLibrary
或UIImageWriteToSavedPhotosAlbum
。
如果您只想将图像保存在自己的应用程序中,请将文件存储在Documents文件夹中。
仅供参考 - 在iOS中使用NSSearchPathForDirectoriesInDomains
时,唯一有用的目录是:
所有其他功能仅适用于macOS。