Проблема в том, что urlString содержит /
, FileManager пытается сохранить данные изображения в несуществующей папке. Это можно исправить, заменив вхождения символа /
на _
.
let fileURL = documentsDirectory.appendingPathComponent((urlString as String).replacingOccurrences(of: "/", with: "_"))
Другое решение - сначала создать папку.
static func saveImageInDocsDir(image: UIImage, urlString: NSString) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
//let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(urlString as String)
print(fileURL)
print(fileURL.path)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = image.jpegData(compressionQuality: 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
// First create a directory
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}