-
Notifications
You must be signed in to change notification settings - Fork 28
Make a relationship with FirebaseAuth
1amageek edited this page Jan 28, 2018
·
3 revisions
Install Firebase/Auth
with CocoaPods.
pod 'Pring'
pod 'Firebase/Auth'
extension Firebase {
@objcMembers
class User: Object {
dynamic var name: String = ""
// MARK: -
static let loggedInNotification: NSNotification.Name = NSNotification.Name(rawValue: "loggedInNotification")
static let loggedOutNotification: NSNotification.Name = NSNotification.Name(rawValue: "loggedOutNotification")
@discardableResult
func signup(_ block: ((DocumentReference?, Error?) -> Void)? = nil) -> [String : StorageUploadTask] {
return save { (ref, error) in
if let error = error {
block?(nil, error)
return
}
NotificationCenter.default.post(name: User.loggedInNotification, object: ref)
block?(ref, nil)
}
}
class func loggedIn(_ block: @escaping () -> Void) -> NSObjectProtocol {
return NotificationCenter.default.addObserver(forName: User.loggedInNotification, object: nil, queue: .main) { (notification) in
print("login")
block()
}
}
class func loggedOut(_ block: @escaping () -> Void) -> AuthStateDidChangeListenerHandle {
return Auth.auth().addStateDidChangeListener { (auth, user) in
if user == nil {
print("logout")
block()
}
}
}
}
}
extension Firebase.User {
/// Return current user
///
/// - Parameters:
/// - completion:
static func current(_ completionHandler: @escaping ((Firebase.User?) -> Void)) {
guard let user: User = Auth.auth().currentUser else {
completionHandler(nil)
return
}
Firebase.User.get(user.uid) { (user, _) in
guard let user: Firebase.User = user else {
// Log out if the user is not saved in Firebase DB
_ = try? Auth.auth().signOut()
completionHandler(nil)
return
}
completionHandler(user)
}
}
}
Auth.auth().signInAnonymously { (user, error) in
if let error: Error = error {
print(error)
return
}
let user: Firebase.User = Firebase.User(id: user!.uid)
user.name = "USER_NAME"
user.signup()
}
Firebase.User.current { [weak self](user) in
guard let user: Firebase.User = user else {
return
}
guard let `self` = self else { return }
// Do something
}