【问题标题】:Second If statement gets called before first statement finished in one function在第一个语句在一个函数中完成之前调用第二个 If 语句
【发布时间】:2017-06-18 12:00:14
【问题描述】:

我有一个函数,里面有 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 下载图像:

- 称为 - 从 facebook 下载图片 被称为 - 从 facebook 下载图片 - 无需从 facebook 下载图片 - 无需从 Facebook 下载图片

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

- 称为 被称为 - 无需从 facebook 下载图片 - 无需从 Facebook 下载图片

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

【问题讨论】:

  • 拜托拜托。提问前先搜索。这已经被问过并回答过无数次了。

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


【解决方案1】:

异步方法!您必须等待完成才能继续下一步。

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

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)
                            }
                        }

                    }
                })
            }

        }
    }
}

【讨论】:

  • 如何对 if 语句执行此操作?你能提供我确切需要添加的内容吗?谢谢。
  • 谢谢拉塞尔!当我在 firebase 的存储中有图像时,它起作用了。但是当我删除个人资料图片以查看该功能是否会再次自动从 facebook 下载图片时,它什么也没做。它也没有显示“从 Facebook 下载图片”打印...
  • OK - 如果您删除了个人资料图片,那么代码是否正在通过错误检查您有// Uh-oh, an error occurred!?如果是这样,那么你需要在那里执行代码
  • 不,我没有收到错误消息。我什么都得不到。我只看到“调用”作为最后的调试输出。然而数据为零。我在“if (data == nil)”语句之前添加了 print(data),它也没有显示输出。但是,当我重新添加个人资料图片时,我会得到下载图像所具有的字节数的输出。问题是我认为“如果(数据==零)”。但是没有图片的时候数据是nil,这怎么可能……
  • 您可能仍然会遇到错误 - 但您会捕获它而不显示任何内容。我会更新代码
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2018-10-01
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
相关资源
最近更新 更多