Search code examples
iosswiftsegueviewcontrolleralertview

How do I switch to another ViewController with perform segue via AlertView?


How do I change to another view controller when the alert view appears? ideally when I press the 'OK' button I want it to programatically change to another view controller.

The following function is what I need to implement:

    func shouldPerformSegueWithIdentifier(_ identifier: String,
                                   sender sender: AnyObject?) -> Bool

Here is my reachability class:

import Foundation
import SystemConfiguration

public class ReachabilityNotification {

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }

        let isReachable = flags == .Reachable
        let needsConnection = flags == .ConnectionRequired

        return isReachable && !needsConnection

    }
}

Here is my ViewController:

import UIKit
import Foundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if Reachability.isConnectedToNetwork() == true {
            print("Internet connection OK")
        } else {
            print("Internet connection FAILED")
            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()

        }

    }
}

Solution

  • Just call the performSegueWithIdentifier(identifier: String, sender: AnyObject?) function where you want to segue to a new view controller. Make sure you use the same string identifier as the segue in your storyboard.

    Give the following a try:

    if ReachabilityNotification.isConnectedToNetwork() == true {
        print("Internet connection OK")
    } else {
        print("Internet connection FAILED")
    
        var connectionAlert = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert)
    
        connectionAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
          performSegueWithIdentifier("SegueIdentifier", sender: self)
          }))
    
        presentViewController(connectionAlert, animated: true, completion: nil)
    }
    

    EDIT:

    Using viewDidLoad() is too early in the process to present the UIAlertController. Try moving your alert into viewDidlAppear.

    import UIKit
    import Foundation
    
    class ViewController: UIViewController {
    
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
    
            if Reachability.isConnectedToNetwork() == true {
                print("Internet connection OK")
            } else {
                print("Internet connection FAILED")
    
                let connectionAlert = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert)
    
                connectionAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { [unowned self] (action: UIAlertAction!) in
                    self.performSegueWithIdentifier("NoConnection", sender: self)
                }))
    
                presentViewController(connectionAlert, animated: true, completion: nil)
            }
        }
    }