Crash when presenting action sheet on iPad

Hi all.

My application crashes whenever I show an action sheet on an iPad, but is fine when running on an iPhone.

Here is the error:

You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.  If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.

Here is my action sheet code:

    func showSheet() {

        let sheet = UIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet)

        

        sheet.addAction(UIAlertAction(title: "Save", style: .default, handler: nil))

        

        sheet.addAction(UIAlertAction(title: "Discard", style: .destructive, handler: nil))

        

        present(sheet, animated: true, completion: nil)

    }

Does anybody have a solution?

Answered by Claude31 in 685383022

You need to provide the position.

Code is usually like this (in this case, popover appears when tapping a button:

            if let ppc = sheet.popoverPresentationController { 
                ppc.sourceView = aButton as UIView
                ppc.sourceRect = (aButton as UIView).bounds
            }

The system has insufficient information to determine where to place the popover on screen. You need to provide this information by using the APIs named in the message. There are some examples of using action sheets in the UIKitCatalog sample code project you can look at.

Accepted Answer

You need to provide the position.

Code is usually like this (in this case, popover appears when tapping a button:

            if let ppc = sheet.popoverPresentationController { 
                ppc.sourceView = aButton as UIView
                ppc.sourceRect = (aButton as UIView).bounds
            }
Crash when presenting action sheet on iPad
 
 
Q