はじめに
個人アプリ作成時にFirebaseUIを使ったTwitterログイン機能を実装したので、
備忘録がてらコマンドの共有をさせていただきます。
また、長すぎて一つの記事に全てを書ききれなかったので3つの記事に分けました。
本記事は、完成形とコードの全容になります。
実装手順についての記事は下記になります。
・【Swift】FirebaseUIを使ったTwitterログイン機能の実装方法②
・【Swift】FirebaseUIを使ったTwitterログイン機能の実装方法③
環境
・Swift version 5.3
・XCode version 12.3
・CocoaPods version 1.10.1
前提として
・CocoaPodsをインストールしていること
・Twitter APIに登録していること
・Firebase consoleに登録していること
完成形
ログイン後Firebase Authentication
コード
import UIKit
import Firebase
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
import UIKit
import Firebase
import FirebaseUI
class ViewController: UIViewController, FUIAuthDelegate {
let authUI = FUIAuth.defaultAuthUI()
let providers: [FUIAuthProvider] = [
FUIOAuth.twitterAuthProvider()
]
override func viewDidLoad() {
super.viewDidLoad()
authUI!.delegate = self
authUI!.providers = providers
checkLoggedIn()
}
// ログイン(ログイン失敗)後に呼ばれるメソッド
func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
// handle user and error as necessary
}
func checkLoggedIn() {
Auth.auth().addStateDidChangeListener{auth, user in
if user != nil{
print("success")
} else {
print("fail")
self.login()
}
}
}
func login() {
let authViewController = authUI!.authViewController()
self.present(authViewController, animated: true, completion: nil)
}
}