简体   繁体   中英

Selecting only PNG and JPEG in Image picker

I would like to limit the user to only pick a PNG or JPEG image from the photo library.

I'm using SwiftUI in my project, this is my UIViewControllerRepresentable

struct ImagePickerRaw: UIViewControllerRepresentable {
    
    @Environment(\.presentationMode) private var presentationMode
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @Binding var selectedImage: UIImage
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerRaw>) -> UIImagePickerController {
        
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.mediaTypes = [UTType.png.identifier, UTType.jpeg.identifier]
        imagePicker.delegate = context.coordinator
        
        return imagePicker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePickerRaw>) {
        
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        
        var parent: ImagePickerRaw?
        
        init(_ parent: ImagePickerRaw) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage,
               let parent = parent {
                parent.selectedImage = image
            }
            
            parent?.presentationMode.wrappedValue.dismiss()
            parent = nil
        }
    }
}

This is how I am trying to limit the user's choice, but I get an error message saying:

ImagePickerDemo[411:12746] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'No available types for source 0

I have also looked at this answer but my app just crashes.

I have tried imagePicker.mediaTypes = [UTType.image.identifier] but that includes gifs.

Is there a way I can limit the user to pick images only (excluding gifs)?

Works as documented:

演示

Check for available types per call (as below) and choose which are to be used

[UIImagePickerController availableMediaTypesForSourceType:
    self.sourceType];

Probably you wanted UIDocumentPickerViewController .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM