2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】Firebase Authを使って爆速でログイン機能を作るためのスニペット

Posted at

firebaseでユーザー登録・ログイン機能を爆速で作るsnippetです。

ユーザー登録

●Firebaseの公式ドキュメントはこちら
https://firebase.google.com/docs/auth/web/manage-users?hl=ja

RegisterViewController.swift
import UIKit
import Firebase

class RegisterViewController: UIViewController {

    @IBOutlet weak var emailTextfield: UITextField!
    @IBOutlet weak var passwordTextfield: UITextField!
    
    @IBAction func registerPressed(_ sender: UIButton) {
        //ユーザーを生成
        if let email = emailTextfield.text, let password = passwordTextfield.text {
            Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
                if let e = error {
                    //エラー分をローカルの言語で表示
                    print(e.localizedDescription)
                } else {
                    //ログイン後の画面に遷移
                    self.performSegue(withIdentifier: "segue identifier" , sender: self)
                }
            }
          
        }
        
    }
    
}

ログイン

LoginViewController.swift
import UIKit
import Firebase

class LoginViewController: UIViewController {

    @IBOutlet weak var emailTextfield: UITextField!
    @IBOutlet weak var passwordTextfield: UITextField!
    

    @IBAction func loginPressed(_ sender: UIButton) {
        //ユーザー認証
        if let email = emailTextfield.text, let password = passwordTextfield.text {
            Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
                if let e = error {
                    print(e.localizedDescription)
                } else {
                    self.performSegue(withIdentifier: "segue identifier", sender: self)
                }
              // ...
            }
        }
        
    }
    
}

ログアウト

LogoutViewController.swift
import Firebase
//中略

@IBAction func logOutPressed(_ sender: UIBarButtonItem) {
        
            let firebaseAuth = Auth.auth()
        do {
          try firebaseAuth.signOut()
            //navigationControllerの先頭に遷移させる
            navigationController?.popToRootViewController(animated: true)
            
        } catch let signOutError as NSError {
          print ("Error signing out: %@", signOutError)
        }
        
    }
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?