Search code examples
iosswiftios8ios9

Present Popover View Controller Swift


When I try to display a popover view controller programmatically it won't work and I don't know why. I've copied from multiple sources on the web and nothing seems to work, I get the same error in the console every time showing Warning: Attempt to present <AddFriendsPopoverViewController> on <MainPageViewController> whose view is not in the window hierarchy! I am lost and can't seem to figure out what the problem is, thanks in advance!

Here is my swift code in my viewDidLoad() function:

let addFriendsPopoverViewController = AddFriendsPopoverViewController()

override func viewDidLoad() {
    super.viewDidLoad()

    if (PFUser.currentUser()?["numberOfFriends"])! as! NSObject == 0 {
        print(PFUser.currentUser()?["numberOfFriends"])

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("AddFriendsPopoverViewController") as! UIViewController

        vc.modalPresentationStyle = UIModalPresentationStyle.Popover
        vc.preferredContentSize = CGSizeMake(50, 50)
        let popoverMenuViewController = vc.popoverPresentationController
        popoverMenuViewController!.permittedArrowDirections = .Any
        popoverMenuViewController!.delegate = self
        popoverMenuViewController!.sourceView = self.view
        popoverMenuViewController!.sourceRect = CGRectMake(
            100,
            100,
            0,
            0)

    self.presentViewController(vc, animated: true, completion: nil)

    }

}

EDIT I figured out that for a popover to work with iPhone the following code is required.

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
    // Return no adaptive presentation style, use default presentation behaviour
    return .None
}

Solution

  • Your view is not in the view hierarchy until it has been presented and not during viewDidLoad:

    Move your code to viewDidAppear:

     if (PFUser.currentUser()?["numberOfFriends"])! as! NSObject == 0 {
    
        addFriendsPopoverViewController.modalPresentationStyle =   UIModalPresentationStyle.Popover
        addFriendsPopoverViewController.preferredContentSize = CGSizeMake(200, 200)
        let popoverMenuViewController = addFriendsPopoverViewController.popoverPresentationController
        popoverMenuViewController!.permittedArrowDirections = .Any
        popoverMenuViewController!.delegate = self
        popoverMenuViewController!.sourceView = self.view
        popoverMenuViewController!.sourceRect = CGRect(
            x: 50,
            y: 50,
            width: 1,
            height: 1)
        presentViewController(
            addFriendsPopoverViewController,
            animated: true,
            completion: nil)
    
    }