前回はデータをリレーションで管理する方法を紹介しました。今回は匿名認証ではなく、会員登録とログインを実装する方法を紹介します。
ログインしていないとタスクを追加できないようにする
未ログイン状態でタスクを追加してしまうと、それは未ログインユーザ全員が読み書きできる状態になってしまいます。そこでタスクの追加ボタンを押せないようにします。
let user = NCMBUser.current() addButton.isEnabled = !(user == nil)
会員登録処理
登録ボタンを押した時の処理を実装します。まずユーザを作成し、userName と password を設定します。
let user = NCMBUser.init() user.userName = userNameTextField.text! user.password = passwordTextField.text!
次に signUpInBackground
で登録処理を実行します。その後は返り値によってアラートを出しているだけです。
user.signUpInBackground({(error) in var params = [String: String]() if error != nil { params["title"] = "Error" params["message"] = error?.localizedDescription } else { params["title"] = "登録完了" params["message"] = "登録完了しました" } let alert = UIAlertController(title: params["title"], message: params["message"], preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alert, animated: true, completion: nil) })
ログイン処理
同様にログイン処理を実装します。ログイン処理は NCMBUser.logInWithUsername
に対してユーザ名、パスワードを指定します。
NCMBUser.logInWithUsername(inBackground: userNameTextField.text!, password: passwordTextField.text!, block: {(user, error) in if error != nil { let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alert, animated: true, completion: nil) } else { self.performSegue(withIdentifier: "backToTop", sender: self) } })
まとめ
会員登録処理、ログイン処理ともに簡単なコードで実装できます。アプリへの会員管理機能を実装する際の参考にしてください。
ここまでの実装は goofmint/NCMB-Swift-iOS-Todo at v3 にアップロードしてあります。実装時の参考にしてください。