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.
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
}
}
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With