【问题标题】:Returning Nil When Running Method from separate class [duplicate]从单独的类运行方法时返回 Nil [重复]
【发布时间】:2020-06-06 20:42:45
【问题描述】:

我有一个视图控制器,它尝试从我的 UserModel 类中调用一个方法,该方法获取用户文档并将返回数据放入用户结构中。但是,它告诉我它在展开可选值时意外发现 nil 。

我的用户模型:

class UserModel {
    var user:User?

    func getUser(userId: String) -> User? {
        let docRef = Firestore.firestore().collection("Users").document(userId)
        // Get data
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                var user:User = User(name: document["name"] as! String, phone: document["phone"] as! String, imageUrl: document["imageUrl"]  as! String)
            } else {
                print("Document does not exist")
            }
        }
        return user!
    }
}

我的结构:

struct User {
    var name:String
    var phone:String
    var imageUrl:String
}    

我的视图控制器:

override func viewDidLoad() {
    super.viewDidLoad()
    userId = Auth.auth().currentUser?.uid
}

override func viewDidAppear(_ animated: Bool) {  
    let model = UserModel()
    user = model.getUser(userId: userId!)
    print(user?.name) 
}

该方法在我的视图控制器中运行良好,所以我知道它正在获取 uid,数据库调用有效,并且值都存在。我已经分别打印了它们。但是,在它自己的类中它不起作用。

有什么想法吗?

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore


    【解决方案1】:

    看起来getDocument 是一个异步函数。因此,您应该使 getUser 异步:

    func getUser(userId: String, completion: @escaping (User?) -> Void) {
        let docRef = Firestore.firestore().collection("Users").document(userId)   
        // Get data
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let user:User = User(name: document["name"] as! String, phone: document["phone"] as! String, imageUrl: document["imageUrl"] as! String)
                completion(user)
            } else {
                completion(nil)
            }
        }
    }
    

    你应该这样称呼它:

    let model = UserModel()
    model.getUser(userId: userId!) { user in
        print(user?.name)
    }
    

    【讨论】:

    • 谢谢罗曼。现在试试。
    • 效果很好。谢谢!
    猜你喜欢
    • 2013-06-13
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    相关资源
    最近更新 更多