Reputation: 1442
Here are my functions to save an image.
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)")
}
and then I'm calling it like this
let path = "/SpotCheck_\(spot.name)_Photo\(indx).jpg"
PhotoManager.savePhoto(with: path, image: photo)
When I call create file is returns false every time and the photo is not saved.
EDIT: The problem was the second line needed to be documentDirectory instead of picturesDirectory. As shown below:
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))[0]
Upvotes: 1
Views: 1188
Reputation: 318774
iOS apps run in a sandbox. You can't write to the Pictures folder.
If you want to add a picture to the user's photo library then use PHPhotoLibrary
or just UIImageWriteToSavedPhotosAlbum
.
If you simply want to save the image within your own app then store the file in the Documents folder.
FYI - when using NSSearchPathForDirectoriesInDomains
in iOS, the only useful directories are:
All the others are only useful in macOS.
Upvotes: 5