I'm creating an app which requires the user to upload image files to the app. In the app I want to obtain its info (dimensions, ecc.) and show it.
Here is what I tried:
var body: some View {
Button(action: {
importing = true
})
{
...
}
.fileImporter(
isPresented: $importing,
allowedContentTypes: [.image]
) { result in
switch result {
case .success(let file):
print("File URL: \(file)")
if controlImage(imageURL: file) {
print("Image uploaded successfully.")
} else {
print("Image doesn't match required dimensions.")
}
case .failure(let error):
print("Failed to load the file: \(error.localizedDescription)")
}
}
}
func controlImage(imageURL: URL) -> Bool {
print("Uploading image: \(imageURL.path)")
let image: NSImage = NSImage(contentsOf: imageURL)!
let imageWidth = image.size.width
let imageHeight = image.size.height
...
}
But when I create the NSImage it says:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
although the image exists and also its URL.
The problem was caused by the File Access options of the Xcode project. By setting them to "Read/Write", the image is read correctly.