使用完成块之外的变量

时间:2016-08-21 17:53:52

标签: swift firebase firebase-realtime-database

我当前从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)
        }

    }

1 个答案:

答案 0 :(得分:1)

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

如果在调用异步completion闭包之前UI的一部分没有意义,那么让viewDidLoad配置UI以使其显式化(可能显示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
}