Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method that all view controllers have access to?

Tags:

xcode

ios

swift

By the time my app is complete, I'll have 50 or so view controllers. In order to use my app the user must have a working internet connection.

I have a code that checks if there is a valid connection, however I would have to add the same code to every viewDidLoad or viewDidAppear for each ViewController (very inefficient in my eyes as I have a Swift file for every VC)

Is there a way to create a "universal" method where I only have the Internet connection code present in one place (and all ViewControllers are able to access it)?

I'm using Swift.

like image 508
dom999999 Avatar asked Dec 04 '25 10:12

dom999999


2 Answers

With this use-case, I should sub-class all ViewControllers to a super class (CommonViewController):

class CommonViewController : UIViewController {
       override func viewDidLoad() {
           super.viewDidLoad() 
           // do your common works for all sub-classes
       }
}

class MyViewController : CommonViewController {
       override func viewDidLoad() {
           super.viewDidLoad()  //call CommonViewController ViewDidLoad
            //... then your work
       }
}
like image 137
Duyen-Hoa Avatar answered Dec 07 '25 00:12

Duyen-Hoa


I just had the opportunity to do an extension now in Swift 2 to help me send alert msgs instead of writing the code down everytime in every view controller i just write down the text string. I used UIAlertController for the newer IOS versions and UIAlertView for the old ones.

Just make a new .swift file and write down the extension you need for the class you want.

import UIKit

extension UIViewController{

func userNamePassAlert(theTitle: String , theMessage: String){

    if #available(iOS 8.0, *) {
        let userTextFieldEmptyAlert = UIAlertController(title: theTitle, message: theMessage, preferredStyle: UIAlertControllerStyle.Alert)
        let userTextFieldEmptyAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in

        })
        userTextFieldEmptyAlert.addAction(userTextFieldEmptyAction)
        self.presentViewController(userTextFieldEmptyAlert, animated: true, completion: nil)

    } else {
        // Fallback on earlier versions
        let userTextFieldEmptyAlert = UIAlertView()
        userTextFieldEmptyAlert.title = theTitle
        userTextFieldEmptyAlert.message = theMessage
        userTextFieldEmptyAlert.addButtonWithTitle("Ok")

        userTextFieldEmptyAlert.show()

    }
}

}

And this is how i call it in my view controllers

else {
         userNamePassAlert("Error Loging In", theMessage: "Username or Password field is empty. Try again")

         }
like image 36
Kegham K. Avatar answered Dec 07 '25 00:12

Kegham K.