Select Video Instead of Image using ImagePickerController - Swift

958 views Asked by At

My situation is that I have a working imagepickercontroller that allows the user to pick an image from their camera roll and display it on an imageview inside the application.

The problem is that I also want to be able to do the same thing with videos, and instead, display the video on an avplayer. I've done some research but couldn't find any good sources.

Can someone show me how to do this? possibly by editing the code below?

Thanks in advance!

This is the code I used for importing and displaying images from cameraroll (all above the viewDidLoad()):

@IBOutlet weak var imageView: UIImageView!

// the image picker controller
var imagePicker = UIImagePickerController()

// this is the button you tap to import your photo
@IBAction func imageViewButtonTapped(_ sender: Any) {
  
    if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
        
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        
        present(imagePicker, animated: true, completion: nil)

    }
}
    

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    var selectedImageFromPicker: UIImage?
    
    if let editedImage = info[.editedImage] as? UIImage{
        selectedImageFromPicker = editedImage
    }else if let originalImage = info[.originalImage] as? UIImage{
        selectedImageFromPicker = originalImage
    }
    
    if let selectedImage = selectedImageFromPicker {
        imageView.image = selectedImage
    }
    
    dismiss(animated: true, completion: nil)
}
1

There are 1 answers

0
Владимир Ковальчук On

try this:

import AVFoundation

class VideoHelper {
    
    static func startMediaBrowser(delegate: UIViewController & UINavigationControllerDelegate & UIImagePickerControllerDelegate, sourceType: UIImagePickerController.SourceType) {
        guard UIImagePickerController.isSourceTypeAvailable(sourceType) else { return }
        
        let mediaUI = UIImagePickerController()
        mediaUI.sourceType = sourceType
        mediaUI.mediaTypes = [kUTTypeMovie as String]
        mediaUI.allowsEditing = true
        mediaUI.delegate = delegate
        delegate.present(mediaUI, animated: true, completion: nil)
    }
}

and you can use this as:

let source = UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) ? UIImagePickerController.SourceType.camera : UIImagePickerController.SourceType.savedPhotosAlbum
        VideoHelper.startMediaBrowser(delegate: self, sourceType: source)