【Swift】Firebase - メアド&パスワードで会員登録/ログイン

 

完成図

会員登録

 

f:id:nekokichi_yos2:20190211113425p:plain

 

ログイン

 

f:id:nekokichi_yos2:20190211113439p:plain

 

パスワードリセット

 

f:id:nekokichi_yos2:20190211113550p:plain

 

解説

 

会員登録

Auth.auth().createUser(withEmail: mailForm.text!, password: passForm.text!) { (user, error) in
   Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in
   })
}
  • メアドとパスワードを入力すると、入力したメアドに認証メールが送られる
  • 認証メールにあるリンクを押せば、会員登録が完了
  • ※注意:パスワードは7文字以上じゃないと会員登録できない

 

f:id:nekokichi_yos2:20190211131002p:plain

f:id:nekokichi_yos2:20190211130949j:plain

 

ログイン

Auth.auth().signIn(withEmail: mailForm.text!, password: passForm.text!) { (user, error) in
}

 

ログアウト

if Auth.auth().currentUser != nil {
         //ログアウト成功
         do {
             try Auth.auth().signOut()
         //ログアウト失敗
} catch let signOutError as NSError { print (signOutError) } }

 

パスワードリセット

Auth.auth().sendPasswordReset(withEmail: resetEmail!, completion: { (error) in
      DispatchQueue.main.async {
          if error != nil {
              self.alert(title: "メールを送信しました。", message: "メールでパスワードの再設定を行ってください。", actiontitle: "OK")
          } else {
              self.alert(title: "エラー", message: "このメールアドレスは登録されてません。", actiontitle: "OK")
          }
      }
})
  • パスワードリセットの際、リセット用のメールが送られる
  • メールに貼ってあるリンクを押せば、リセット後のパスワードを入力
  • 入力すれば、パスワードが更新される

 

f:id:nekokichi_yos2:20190211131007j:plain

f:id:nekokichi_yos2:20190211130958p:plain

f:id:nekokichi_yos2:20190211130953p:plain

 

ストーリーボード

 

f:id:nekokichi_yos2:20190211113111p:plain

 

ソースコード

会員登録画面

import UIKit
import Firebase

class SignUp: UIViewController,UITextFieldDelegate {

    //メールアドレスとパスワード
    @IBOutlet weak var mailForm: UITextField!
    @IBOutlet weak var passForm: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //UITextFieldのデリゲート
        mailForm.delegate = self
        passForm.delegate = self
        
        //UITextFieldに枠線,角丸を施す
        mailForm.layer.borderWidth = 1
        mailForm.layer.cornerRadius = 10
        passForm.layer.borderWidth = 1
        passForm.layer.cornerRadius = 10
    }
    
    //会員登録
    @IBAction func signup(_ sender: Any) {
        //2つのフォームが入力されてる場合
        if mailForm.text != "" && passForm.text != "" {
            //入力したパスワードが7文字以上の場合
            if (passForm.text?.count)! > 6  {
                //会員登録開始
                Auth.auth().createUser(withEmail: mailForm.text!, password: passForm.text!) { (user, error) in
                    //ログイン成功
                    if error == nil {
                        //登録メアドに確認のメールを送る
                        Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in
                            //エラー処理
                            if error != nil {
                                let storyboard = UIStoryboard(name: "Main", bundle:Bundle.main)
                                let rootViewController = storyboard.instantiateViewController(withIdentifier: "main")
                                UIApplication.shared.keyWindow?.rootViewController = rootViewController
                            } else {
                            }
                        })
                    //ログイン失敗
                    } else {
                        self.alert(title: "エラー", message: "ログイン失敗", actiontitle: "OK")
                    }
                }
            //入力したパスワードが6文字以下の場合
            } else {
                self.alert(title: "エラー", message: "7文字以上のパスワードを入力してください。", actiontitle: "OK")
            }
        //いずれかのフォームが未入力の場合
        } else {
            self.alert(title: "エラー", message: "入力されてない箇所があります。", actiontitle: "OK")
        }
    }

    //ログイン画面へ移行
    @IBAction func changeToLogin(_ sender: Any) {
        performSegue(withIdentifier: "changesignin", sender: nil)
    }
    
    //アラート
    func alert(title:String,message:String,actiontitle:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: actiontitle, style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
   
    //Returnでキーボードを閉じる
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    //画面外タップでキーボードを閉じる
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        mailForm.resignFirstResponder()
        passForm.resignFirstResponder()
    }

}

ログイン画面/ログアウト

import UIKit
import Firebase

class SignIn: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var mailForm: UITextField!
    @IBOutlet weak var passForm: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mailForm.delegate = self
        passForm.delegate = self
        
        mailForm.layer.borderWidth = 1
        mailForm.layer.cornerRadius = 10
        passForm.layer.borderWidth = 1
        passForm.layer.cornerRadius = 10
    }
    
    @IBAction func remindPassword(_ sender: Any) {
        let remindPasswordAlert = UIAlertController(title: "パスワードをリセット", message: "メールアドレスを入力してください", preferredStyle: .alert)
        remindPasswordAlert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
        remindPasswordAlert.addAction(UIAlertAction(title: "リセット", style: .default, handler: { (action) in
            let resetEmail = remindPasswordAlert.textFields?.first?.text
            Auth.auth().sendPasswordReset(withEmail: resetEmail!, completion: { (error) in
                DispatchQueue.main.async {
                    if error != nil {
                        self.alert(title: "メールを送信しました。", message: "メールでパスワードの再設定を行ってください。", actiontitle: "OK")
                    } else {
                        self.alert(title: "エラー", message: "このメールアドレスは登録されてません。", actiontitle: "OK")
                    }
                }
            })
        }))
        remindPasswordAlert.addTextField { (textField) in
            textField.placeholder = "test@gmail.com"
        }
        self.present(remindPasswordAlert, animated: true, completion: nil)
    }
    
    @IBAction func signin(_ sender: Any) {
        //ちゃんと入力されてるかの確認
        if mailForm.text != "" && passForm.text != "" {
            Auth.auth().signIn(withEmail: mailForm.text!, password: passForm.text!) { (user, error) in
                if error == nil {
                    //ホーム画面へ移行
                    let storyboard = UIStoryboard(name: "Main", bundle:Bundle.main)
                    let rootViewController = storyboard.instantiateViewController(withIdentifier: "main")
                    UIApplication.shared.keyWindow?.rootViewController = rootViewController
                } else {
                    self.alert(title: "エラー", message: "メールアドレスまたはパスワードが間違ってます。", actiontitle: "OK")
                }
            }
        } else {
            self.alert(title: "エラー", message: "入力されてない箇所があります。", actiontitle: "OK")
        }
    }
    
    @IBAction func changeTosignup(_ sender: Any) {
        performSegue(withIdentifier: "changeTosignup", sender: nil)
    }
    
    //アラート
    func alert(title:String,message:String,actiontitle:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: actiontitle, style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        mailForm.resignFirstResponder()
        passForm.resignFirstResponder()
    }

}

 

ログアウト

import UIKit
import Firebase

class ViewController: UIViewController{
    
    //ログアウト
    @IBAction func signout(_ sender: Any) {
        //ログアウト開始
        if Auth.auth().currentUser != nil {
            //ログアウト成功
            do {
                try Auth.auth().signOut()
            //ログアウト失敗
            } catch let signOutError as NSError {
                print (signOutError)
            }
        } else {
            return
        }
        
        //ログイン画面に戻る
        let storyboard = UIStoryboard(name: "Main", bundle:Bundle.main)
        let rootViewController = storyboard.instantiateViewController(withIdentifier: "gosignin")
        UIApplication.shared.keyWindow?.rootViewController = rootViewController
    }
    
}