Swift: Displaying a UIImagePickerController in iOS 9 using non-deprecated classes


In iOS there have been so many classes come and go for the presentation of alerts and actions, and there's so much documentation (and so many tutorials) that point to deprecated approaches, that it can be a bit mind boggling where to start when the compiler presents you with a warning. And this is made even more difficult by many deprecated classes having very similar names to newer or non-deprecated classes for doing similar things. So here's the latest way to perform a common task: presenting an image picker.

The old way

We'll start with the old, deprecated, way of displaying a UIImagePickerController first:
@IBAction func selectImage(sender: AnyObject) {
      
    let imgPicker = UIImagePickerController()
    imgPicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    
    let popper = UIPopoverController(contentViewController: imgPicker)
    popper.presentPopoverFromBarButtonItem(sender as! UIBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)

}
This employs the (deprecated) UIPopoverController class.

The new way

The new way to do the same thing uses the UIPopoverPresentationController class, but we don't instantiate it directly. We first set the image picker modal presentation style to UIModalPresentationStyle.Popover and then retrieve the image picker's UIPopoverPresentation Controller after the presentation method has been called and set all the necessary properties there:
@IBAction func selectImage(sender: AnyObject) {
      
    let imgPicker = UIImagePickerController()
    imgPicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    imgPicker.modalPresentationStyle = UIModalPresentationStyle.Popover
        
    self.presentViewController(imgPicker, animated: true, completion: nil)
    
    let popper = imgPicker.popoverPresentationController
    // returns a UIPopoverPresentationController
    popper?.barButtonItem = sender as? UIBarButtonItem

}
This code can be used in iOS 8 and later, and the best thing is that its behaviour adapts to different size classes automatically. This means on an iPhone you'll see a full screen presentation as you should rather than a popover.

Notes

I haven't entered into delegation and handling of the image picker responses here, the purpose of this post has simply been to consider the use of UIImagePickerController without resorting to deprecated classes and methods.


Endorse on Coderwall

Comments