Search code examples
iosswiftuistoryboardsegueviewdidload

check connection and perform a segue to second view controller


I met strange thing and don't understand why it is not working.

I am using this project to check type of internet connection. My idea was to check connection and jump to login page or stay on first controller if device is not connected.

Here is my code:

class ViewController: UIViewController {

    @IBOutlet weak var connectionTypeLabel: UILabel!

    @IBAction func test(_ sender: Any) {


        self.performSegue(withIdentifier: "showLogin", sender: self)


    }


    let status = Reach().connectionStatus()



    override func viewDidLoad() {
        super.viewDidLoad()




        self.connectionTypeLabel.text = ""

        switch self.status {
        case .unknown, .offline:

            self.connectionTypeLabel.text = "No Connected"

        case .online(.wwan):

            self.connectionTypeLabel.text = "Connected!"

            self.performSegue(withIdentifier: "showLogin", sender: self)            
        case .online(.wiFi):

            self.connectionTypeLabel.text = "Connected!"
            self.performSegue(withIdentifier: "showLogin", sender: self)        
        }


    }

I was trying both viewDidLoad and viewWillAppear methods.

I really dont understand why text label is changing its text correctly and program doesn't go to login view controller.

I created a test button to check if performSegue function is working and it is working just fine. I have no clue why it is not working inside viewDidLoad method


Solution

  • Try move your check to viewWillAppear, since performSegue wont work correctly on viewDidLoad and warp in dispatch time like:

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.02, execute: {
         self.performSegue(withIdentifier: "showLogin", sender: self)  
    })
    

    Better approach is dump the vc and move the checking code to AppDelegate in didFinishLaunchingWithOptions like:

    case .online(.wwan), .online(.wiFi):
       let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginVC")
       window?.rootViewController = loginVC
       window?.makeKeyAndVisible()
    

    For no connection do similar but change loginVC with noConnectionVC, you will need to give your vc in storyboard an identifier to initialize it in code