一尘不染

在完成块之外使用变量

swift

目前,我正在从Firebase检索数据,将数据放入NSObject,然后放入完成块。完成块内部的项目存储为变量userBinfos。变量userBinfos仅在完成块内部工作,我想在完成外部使用它

var userBinfos = userObject()
    override func viewDidLoad() {
        super.viewDidLoad()

        userBinfo { (user) in
        self.userBinfos = user

        }  
//I want to use to variable here but it does not work 
        print(self.userBinfos.email)

    }


    func userBinfo(completion: (userObject) -> ()) {

        let dbFir = FIRDatabase.database().reference()

        let firRef = dbFir.child("frontEnd/users/\(userId)")

        firRef.observeEventType(.Value, withBlock: { snapshot in

            let userDict = snapshot.value as! [String: AnyObject]
            self.name.text = userDict["firstname"] as? String
            self.userBio.text = userDict["userBio"] as! String

            var user = userObject()

            user.firstName = userDict["firstname"]
            user.lastName = userDict["lastname"]
            user.email = userDict["email"]
            user.profileImageUrl = userDict["profileImageUrl"]
            user.userBio = userDict["firstname"]
            user.userId = userDict["firstname"]

                   dispatch_async(dispatch_get_main_queue(), {
            completion(user)

            })

        }) { (error) in
            print(error)
        }

    }

阅读 245

收藏
2020-07-07

共1个答案

一尘不染

completion参数的全部目的userBinfo是提供一种机制,用于在异步observeEventType调用时得到通知。因此,将代码取决于闭包
内部 该异步方法的完成情况userBinfo { user in ... }

而且,如果在completion调用异步关闭之前UI的一部分没有意义,则需要viewDidLoad配置UI使其显式(也许显示a
UIActivityIndicatorView或其他内容),然后在完成处理程序中删除这些内容。

override func viewDidLoad() {
    super.viewDidLoad()

    // do whatever you want to let the user know that something asynchronous
    // is happening, e.g. add a spinning `UIActivityIndicatorView` or whatever

    userBinfo { user in
        self.userBinfos = user

        // Update the UI here, including removing anything we presented to let
        // the user know that the asynchronous process was underway. If you were
        // dealing with UITableView`, you'd call `tableView.reloadData()` here.
    }

    // but not here
}
2020-07-07