首页 > 解决方案 > 如何从用户 ID 中获取用户名和照片网址 - Swift 和 Firebase

问题描述

我有另一个 swift 文件,其中存储了 Firebase 中的所有当前用户信息,但由于某种原因它无法正常工作,看起来好像没有数据。如果有人可以帮助我找出我做错了什么,我将不胜感激。

这是我的firebase架构...... 在此处输入图像描述

class UserService {


    static var currentUserProfile:UserProfile?

    static func observeUserProfile(_ uid: String, completion: @escaping ((_ userProfile: UserProfile?)-> ()) ) {

        let userRef = Database.database().reference().child("users/\(uid)")
        userRef.observe(.value) { (snapshot) in
            var userProfile:UserProfile?

            if let dict = snapshot.value as? [String: Any],
                let username = dict["username"] as? String,
                let photoUrl = dict["photoUrl"] as? String,
                let url = URL(string: photoUrl) {

                userProfile = UserProfile(uid: snapshot.key, username: username, photoUrl: url)

            }
            completion(userProfile)
        }
    }

}

然后我使用用户名和 photoUrl 在我的 setValue 函数中使用它......

func sendDataToDatabaseFound(address: String, breed: String, phone: String, photoUrl: String, timestamp: String) {
        //por the time being photoUrl:String - wasn't added because I can't get the downloadURL
        //         func sendDataToDatabase(address: String, breed: String, phone: String, lostfound: String, photoUrl: String)
        var ref: DatabaseReference!
        ref = Database.database().reference()
        let postsReference = ref.child("posts").child("found")
        let newPostId = postsReference.childByAutoId().key
        let newPostReference = postsReference.child(newPostId)
        // Still need to add the "photo": photoUrl --> newPostReference.setValue(["photoUrl": photoUrl]
        let toId = Auth.auth().currentUser?.uid
        newPostReference.setValue( ["address": address, "breed": breed, "phone": phone,"photoUrl": photoUrl, "timestamp": timestamp, "author": ["userid": toId, "username": UserService.currentUserProfile?.username, "profilePhotoUrl": UserService.currentUserProfile?.photoUrl.absoluteString]]) { (error, ref) in
            if error != nil {
                ProgressHUD.showError(error!.localizedDescription)
                return
            }

标签: swiftfirebasefirebase-realtime-databaseauthoruid

解决方案


如果您查看 的代码Auth.auth().currentUser,您会发现它属于刚刚在 Swift 中FIRUser调用的类。是 的子类,它具有许多特征,包括 providerID、uid、displayName、photoURL、email 和 phoneNumber。UserFIRUserFIRUserInfo

您可以像访问uid.currentUser

if let user = Auth.auth().currentUser {
    let providerID: String = user.providerID
    let uid: String = user.uid
    let displayName: String = user.displayName
    let photoURL: String = user.photoURL
    let email: String = user.email
}

推荐阅读