Skip to content

Instantly share code, notes, and snippets.

@vikdenic
Created December 8, 2015 00:06
Show Gist options
  • Select an option

  • Save vikdenic/0f95ef77f56fc6439a38 to your computer and use it in GitHub Desktop.

Select an option

Save vikdenic/0f95ef77f56fc6439a38 to your computer and use it in GitHub Desktop.
Class method on PFUser subclass that throws
// In this example, we will create a class method for our PFUser subclass
// The method will register a new user, but throw certain error types for us to exhaustively handle
// First, we define our errors as an enum that conforms to ErrorType
// Here we anticipate common error cases
enum SignUpError: ErrorType {
case EmptyFields
case TooLong
case TooShort
}
//Here is our class in which we define the method we will later call
class User: PFUser {
// This class method will create a new user, taking in the username and password as parameters
// Notice we add "throws" at the end of the method declaration
// And within the method, we guard against the various cases. And throw the appropriate error type within them
class func registerNewUser(username : String!, password : String!, completed:(error : NSError!) -> Void) throws
{
guard username.characters.count > 0 || password.characters.count > 0 else {
throw SignUpError.EmptyFields
}
guard password.characters.count > 6 else {
throw SignUpError.TooShort
}
guard password.characters.count < 16 else {
throw SignUpError.TooLong
}
let newUser = User()
newUser.username = username.lowercaseString
newUser.password = password.lowercaseString
newUser.signUpInBackgroundWithBlock { (succeeded, signUpError) -> Void in
completed(error: signUpError)
}
}
}
//Then, (for example) in a view-controller where we call that method we can react to the error types being thrown:
class SignUpViewController: UIViewController {
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
// Within a "do", we call our custom class method that "throws" using "try"
// Following the "do", we "catch" the various errorTypes (of our enum) that can be thrown
@IBAction func onSignUpButtonTapped(sender: UIButton) {
do {
try User.registerNewUser(usernameTextField.text, password: passwordTextField.text, completed: { (error) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
} catch SignUpError.EmptyFields {
print("empty fields")
} catch SignUpError.TooShort {
print("too short")
} catch SignUpError.TooLong {
print("too long")
} catch {
print("something else went wrong")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment