Swift代码报错:无法将URL类型转换为预期的Bool类型
Hey there, let's break down this error and get your image-saving code working properly!
What's Causing the Error?
The root issue is that you added try! before calling FileManager.default.url(...)—but this method does not throw errors at all.
try! is only meant for functions marked with throws (functions that can fail and throw an error). When you slap try! in front of a non-throwing function that returns a URL, the Swift compiler gets confused. It tries to interpret this as a boolean condition (since try! expects a throwable expression), hence the weird type mismatch error about converting URL to Bool.
Quick Fix for the Main Error
Just remove the unnecessary try! from that line. The url(for:in:appropriateFor:create:) method safely returns a URL without throwing, so no error handling is needed here:
let document = FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
Bonus: Fixing Other Potential Issues in Your Code
While we're at it, let's clean up a few other things that could cause crashes or unexpected behavior:
Incorrect
isDirectoryparameter: When appending the image filename, you setisDirectory: true—but1.jpgis a file, not a directory. You can either set it tofalseor omit the parameter entirely (it defaults tofalse):let imgUrl = document.appendingPathComponent("1.jpg")Risky force unwraps: Using
!to unwrapUIImage(named: "1.jpg")andUIImageJPEGRepresentation(...)can crash your app if the image doesn't exist or the conversion fails. Use aguardstatement to handle these optionals safely:guard let image = UIImage(named: "1.jpg"), let imageData = UIImageJPEGRepresentation(image, 0.8) else { print("Failed to load image or convert to JPEG data") return }Backwards file existence check: Your original code only writes the image if the file already exists—this is probably the opposite of what you want. If you want to create the image (or overwrite it), you can skip the
fileExistscheck entirely and just write the data.
Full Corrected Code
Here's the cleaned-up version of your function with all fixes applied:
private func saveImages() { // Get the documents directory URL (no try! needed) let document = FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) print(document) // Create the full URL for our image file let imgUrl = document.appendingPathComponent("1.jpg") print(imgUrl.path) // Safely load the image and convert to JPEG data guard let image = UIImage(named: "1.jpg"), let imageData = UIImageJPEGRepresentation(image, 0.8) else { print("Could not load image or convert to JPEG data") return } // Write the image data to disk do { try imageData.write(to: imgUrl) print("image added successfully") } catch { print("image not added: \(error.localizedDescription)") } }
内容的提问来源于stack exchange,提问作者sailendra muduli

