present alert view in main view controller (called

2019-08-09 03:22发布

问题:

I have tow views in my app. A main view(ViewController.swift) and a sidebar(SideBar.swift). If I tapp a button in the sidebar an UIAlertViewshould be displayed (I call a function in ViewController.swift). But the app crashes because the main view is nil. Do you know how I can fix this?

My code in the function (display alert):

    let alertView = UIAlertController(title: "You need to log in first", message: "To access the special features of the app you need to log in first.", preferredStyle: .Alert)
    alertView.addAction(UIAlertAction(title: "Login", style: .Default, handler: { (alertAction) -> Void in
    }))
    alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    self.presentViewController(alertView, animated: true, completion: nil)

Crash log:

0x724160 <+60>:  bl     0x75961c                  ; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded> of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2)
->  0x724164 <+64>:  trap   

回答1:

There are two solutions that come to my mind.

  1. Declare a protocol and use the delegate to pass on the alert call to the MainView.

First, define a protocol in our SideBar.swift (Lets call it AlertDelegate).

 protocol AlertDelegate {

    func alertMain()

}

Now we create a delegate variable in SideBar.swift.

var alertDelegate:AlertDelegate?

Then we make our MainView (ViewController.swift) adhere to the AlertDelegate protocol.

class ViewController: UIViewController,foo,bar,AlertDelegate

And add in the function for the AlertDelegate protocol. Here is where you would put your UIAlertController code.

func alertMain(){

 //Present UIAlertController
}

Finally, we have to set out ViewController to the delegate alertDelegate

  1. Present your UIAlertController using AppDelegate KeyWindow. I probably wouldn't recommend this method, but this is how you would do it.

     UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)