LoginSignup
0
3

More than 3 years have passed since last update.

Swift Firebase 匿名認証(anonymously Authentication)

Posted at

概要

  • iOSアプリを開発している
  • Firebaseを使いたい
  • ユーザーを識別したい
  • 気軽に利用できるアプリにしたい
  • 無駄にセキュリティ情報を保持したくない(メールアドレスは管理したくない)

説明

現在開発中のアプリ(クイズのオンライン対戦)でユーザーの識別が必要となりました。
概要のとおり、個人アプリを開発時に良くあるケースですが、
Qiitaなどでサンプルコードがすぐに見つからないので共有しておきます。
(Firebase Storageによる画像の登録は次回共有します)

要件

  • アプリ起動時に匿名認証する
    • ユーザーが存在する場合
      • NavigationBarにユーザーが設定したアイコンとニックネームを表示
    • ユーザーが存在しない場合
      • NavigationBarにdefaultアイコンとニックネーム(未設定)を表示

結果

サンプルコード

import UIKit
import Firebase

class TopViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        signInAnonymously()
    }

    private func signInAnonymously() {
        Auth.auth().signInAnonymously { [weak self] (authResult, error) in
            guard let user = authResult?.user else { return }
            self?.configureNavigationBar(user: user)
        }
    }

    private func configureNavigationBar(user: User) {
        let nickName = user.displayName ?? "未設定"
        let button = UIButton(type: .system)
        button.setTitle(" \(nickName)", for: .normal)
        button.setTitleColor(UIColor.black, for: .normal)
        button.contentMode = .scaleAspectFit
        button.imageView?.layer.cornerRadius = 20
        button.imageView?.layer.borderWidth = 0.5
        button.imageView?.layer.borderColor = UIColor.lightGray.cgColor
        button.imageView?.clipsToBounds = true
        let imageRef = Storage.storage().reference().child("images/\(user.uid).jpg")
        imageRef.getData(maxSize: 1024 * 1024) { [weak self] data, error in
            guard let self = self else { return }
            let image: UIImage?
            if let _ = error {
                image = UIImage(named: "default")
            } else {
                image = UIImage(data: data!)?.reSizeImage(reSize: CGSize(width: 40, height: 40))
            }
            button.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
        }
    }
}


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