How to make ActionSheet style AlertController work on Devices of type iPad? (Swift 3, Xcode 8)

I had a button on my Application that would open actionsheet style alertcontroller when clicked. It worked fine on iPhones, but when I tried it on iPads, it crashed my App.

iPad devices present actionsheet type alertcontroller as popoverPresentationController, so you have to handle it as a special case, meaning you have to specify sourceView(button, image, etc.) for that popoverPresentationController.

let imageView = UIImageView() // To-Do: populate constructor
let alert = UIAlertController() // To-Do: populate constructor
let action = UIAlertAction()// T0-Do: populate constructor
alert.addAction(action) // Add as many actions you need
if let presenter = alert.popoverPresentationController {
presenter.sourceView = imageView
presenter.sourceRect = imageView.bounds
}
present(alert, animated: true, completion: null)

The code above would handle both the devices (iPhones & iPads). In case of iPhones, it would not make into that “if let” statement, making them work normally. In case of iPads, it would go to that “if let” block, and set the souceView. I have taken imageView as an example, but it could be anything inheriting from UIView.