0
1

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 3 years have passed since last update.

Swift Firebaseを使ってみよう FirebaseAuth編

Posted at

FirebaseAuth導入

※この記事ではFirebaseコンソールでの設定は終わっているものとしています。
まずはターミナルを開いてプロジェクトに移動しましょう。

cd /Users/[ユーザー名]/Desktop/[プロジェクト名]/

移動ができているか心配の方はpwdコマンドを実行してください。
移動したらポッドファイルの作成をします。

pod init

コマンドを実行するとpodfileが作成されています。
確認方法はlsコマンドを実行しましょう。
ちゃんと作成されていたら

open podfile

でファイルを開きます。
開いたらこんな感じに編集してください。

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'FirebaseTest' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FirebaseTest
  // 追加
  pod 'Firebase/Auth'
end

もう一度ターミナルに戻ります。
戻ったら次のコマンドを打ちます。

pod intall

これでFirebaseAuthが使えるようになります。

使ってみよう 新規ユーザー登録編

ターミナルで

open [プロジェクト名].xcworkspace

と打ってください。
Finderから開いても大丈夫です。
拡張子が.xcodeprojじゃなくて.xcworkspaceですので間違えないようにしてください。
開いたらViewControllerの編集をしましょう。

ViewController.swift
class ViewController: UIViewController {

    private var emailFiled = UITextField()
    private var passwordField = UITextField()
    private let authButton: UIButton = {
        let button = UIButton()
        button.setTitle("登録", for: .normal)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        emailFiled = initField(placeholder: "email")
        passwordField = initField(placeholder: "password")
        authButton.addTarget(self, action: #selector(didTapAuthButton), for: .touchUpInside)
        
        view.addSubview(emailFiled)
        view.addSubview(passwordField)
        view.addSubview(authButton)
        emailFiled.frame = .init(x: 50, y: 100, width: view.frame.size.width-100, height: 40)
        passwordField.frame = .init(x: 50, y: 160, width: view.frame.size.width-100, height: 40)
        authButton.frame = .init(x: 50, y: 220, width: view.frame.size.width-100, height: 40)
    }
    
    @objc func didTapAuthButton() {
        
    }
    
    private func initField(placeholder: String) -> UITextField {
        let field = UITextField()
        field.placeholder = placeholder
        field.autocorrectionType = .no
        field.autocapitalizationType = .none
        field.layer.borderWidth = 1
        field.layer.borderColor = UIColor.black.cgColor
        if placeholder == "password" {
            // 入力した文字を隠す
            field.isSecureTextEntry = true
        }
        return field
    }
}

こんな感じにViewを設定しましょう。
さあ、お待たせしました。
FirebaseAuthを使っていきます。
didTapAuthButton の中に処理を書いていきます。
変更点だけ書きます。

import FirebaseAuth

class ViewController: UIViewController {
    @objc func didTapAuthButton() {
        guard let email = emailFiled.text, let password = passwordField.text else {return}
        Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
            guard let user = result?.user, err == nil else {
                print("error: ", err!)
                return
            }
            let userEmail = user.email
            print("email: ", userEmail ?? "")
        }
    }
}

新しくユーザーを作成するのはたったのこれだけ
なんならcreateUserの後に実行したい処理がなければAuth.auth().createUser(withEmail: email, password: password)だけで済みます。
まあクロージャの中身空にしたまま使うことなんてほぼないと思いますけど。

使ってみよう ログイン・ログアウト編

ログインも早速コードをみてみましょう。

@objc func didTapAuthButton() {
        guard let email = emailFiled.text, let password = passwordField.text else {return}
        Auth.auth().signIn(withEmail: email, password: password)
}

これだけでログイン機能ができます。めっちゃ簡単ですね。

ログアウト機能もこんな感じでできます。

@objc func didTapAuthButton() {
        do {
            try Auth.auth().signOut()
        } catch(let err) {
            print(err)
        }
}

ログアウトは例外処理が発生しますので例外処理って何?って思う方はこちらを参照してください。
Swift 4.0 エラー処理入門

他にも電話番号でログインしたりする機能も簡単に実装できるので調べてみてください。
今回はここまで。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?