SceneDelegate ログインのview周りの処理を書く場所
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let window = UIWindow(windowScene: windowScene)
let vc: UIViewController
if let user = Auth.auth().currentUser {
GIDSignIn.sharedInstance()?.restorePreviousSignIn()
guard let email = user.email else { return }
User.instantiate(with: user.uid, name: user.displayName ?? email, email: email)
vc = UIStoryboard(name: DiaryIndexController.className, bundle: nil).instantiateInitialViewController()!
}
else {
vc = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
}
window.rootViewController = vc
self.window = window
window.makeKeyAndVisible()
}
User.instantiate
import Foundation
import Firebase
import GoogleSignIn
final class User {
private(set) static var loggedIn: User?
private static var listener: ListenerRegistration? {
willSet { listener?.remove() }
}
class func instantiate(with id: String, name: String, email: String) {
listener = Firestore.firestore().collection(USER_REF).document(id).addSnapshotListener { (snapshot, error) in
if let error = error{
debugPrint(error)
}
guard let document = snapshot?.data() else {
self.createNewUserData(id: id, fullName: name, email: email)
return
}
let isLoggedIn = loggedIn != nil
if !isLoggedIn {
loggedIn = User()
loggedIn?.user_id = id
}
loggedIn?.name = document["name"] as? String ?? name
loggedIn?.email = document["email"] as? String ?? email
loggedIn?.points = document["point"] as? Int ?? 0
loggedIn?.photo = document["photo"] as? String ?? ""
}
}
createNewUserData
private class func createNewUserData(id: String, fullName: String?, email: String?) {
let fullName = fullName ?? "name"
let email = email ?? "e-mail"
let db = Firestore.firestore().collection(USER_REF).document(id)
db.setData([
NAME : fullName,
EMAIL: email,
CREATED_AT: FieldValue.serverTimestamp(),
UPDATED_AT: FieldValue.serverTimestamp()
])
User.instantiate(with: id, name: fullName, email: email)
}