在第一个语句在一个函数中完成之前调用第二个If语句

时间:2017-02-01 16:32:48

标签: swift function if-statement firebase firebase-realtime-database

我有一个函数,里面有2个if语句。代码:

func pictureFromFirebase(loginMethod: Int)
    {
    if loginMethod == 0 //FB
    {
        var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height":300, "width":300, "redirect":false], httpMethod: "GET")
        let profilePicRef = storageRef.child((user?.uid)!+"/profile_pic.jpg")
        profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in
            if let error = error {
                // Uh-oh, an error occurred!
            } else {
               if (data != nil)
               {
                print("no need to download image from facebook")
                self.profileImage.image = UIImage (data: data!)
                }
            }
        }
        if profileImage.image == nil
        {
        print("downloading image from facebook")
        profilePic?.start(completionHandler: {(_ connection, _ result, _ error) -> Void in
            if (error == nil)
            {
                if let dictionary = result as? [String:Any], let data = dictionary["data"] as? [String:Any],
                    let urlPic = data["url"] as? String {
                    if let imageData = NSData(contentsOf: NSURL(string: urlPic)! as URL)
                    {
                        let uploadTask = profilePicRef.put(imageData as Data, metadata: nil){
                         metadata, error in
                            if (error == nil)
                            {
                                let downloadUrl = metadata!.downloadURL
                            }
                            else
                            {
                                print("error in downloading image")
                            }
                        }
                        self.profileImage.image = UIImage(data: imageData as Data)
                    }
                }

            }
        })
    }
    }
    }

只有在触发此功能时才会调用它:

FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
            print("called")
            if let user = user {
                if(activeUser != user){
                let name = user.displayName
                self.profileName.text = name
                self.pictureFromFirebase(loginMethod: 0)
                }
            }

这是调试的正常输出,当我已经设置了图像时,不需要从Facebook下载图像:

-called - 从Facebook下载图像 -called - 从Facebook下载图像 - 无需从Facebook下载图像 - 无需从Facebook下载图片

当我删除整个第二个if语句时,这是调试的输出(如果profileImage.image == nil):

-called -called - 无需从Facebook下载图像 - 无需从Facebook下载图片

从我所看到的,除了函数被调用两次也是错误的,第二个语句在第一个语句执行之前被调用。由于第一个语句在设置profileImage之前需要一段时间,因此当第二个if语句检查此值时它为nil。我怎样才能确保不再发生这种情况?谢谢。

1 个答案:

答案 0 :(得分:2)

异步方法!在继续下一步之前,您必须等待完成。

将第二个块放在第一个完成处理程序中 - 就像这样

func pictureFromFirebase(loginMethod: Int)
{
    if loginMethod == 0 //FB
    {
        var profilePic = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["height":300, "width":300, "redirect":false], httpMethod: "GET")
        let profilePicRef = storageRef.child((user?.uid)!+"/profile_pic.jpg")
        profilePicRef.data(withMaxSize: 1 * 1024 * 1024) { data, error in
            if let error = error {
                // Uh-oh, an error occurred!
                // but we don't need to do anything yet.  Try to download the profile pic
            }
            if (data != nil)
            {
                print("no need to download image from facebook")
                self.profileImage.image = UIImage (data: data!)
            }
            else
            {
                // THIS IS THE BLOCK THAT HAS BEEN MOVED
                // WHICH WILL NOW BE EXECUTED IN TWO CONDITIONS - 
                // 1. AN ERROR IN THE DOWNLOAD
                // 2. NO PROFILE PIC AVAILABLE
                print("downloading image from facebook")
                profilePic?.start(completionHandler: {(_ connection, _ result, _ error) -> Void in
                    if (error == nil)
                    {
                        if let dictionary = result as? [String:Any], let data = dictionary["data"] as? [String:Any],
                            let urlPic = data["url"] as? String {
                            if let imageData = NSData(contentsOf: NSURL(string: urlPic)! as URL)
                            {
                                let uploadTask = profilePicRef.put(imageData as Data, metadata: nil){
                                    metadata, error in
                                    if (error == nil)
                                    {
                                        let downloadUrl = metadata!.downloadURL
                                    }
                                    else
                                    {
                                        print("error in downloading image")
                                    }
                                }
                                self.profileImage.image = UIImage(data: imageData as Data)
                            }
                        }

                    }
                })
            }

        }
    }
}