Reputation: 7318
In order to avoid duplicate code, I would like to create a separate class file to handle all errors in my app (mostly returned from backend blocks) and present them to the user in an alert popup that user can close. So I've created a class, and put this inside:
import Foundation
class Errors {
func errors(errorText: String, currentViewController: UIViewController) {
var alert = UIAlertController(title: "There was an error", message: errorText, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))
currentViewController.presentViewController(alert, animated: true, completion: nil)
}
}
then when invoking this function from any viewController I do this:
Errors().errors("Error text", currentViewController: GameScreenViewController)
this won't work and compiler wants me to add () after GameScreenViewController which cause the app to behave improperly.
I guess this is not the right way to do this, can you please advise on how to do this properly. Please answer in Swift.
Upvotes: 0
Views: 99
Reputation: 5555
you need to invole it with 'self' instead of GameScreenViewController as second argument from within your view controller you like to display the error.
what you are passing currently is not an object but merely a classname.
class GameScreenViewController : UIViewConroller {
// your viewcontroller logic
func showError(){
// try this:
Errors().errors("Error text", currentViewController: self)
}
}
Upvotes: 1