Ios 异步任务中的swift Firebase返回

Ios 异步任务中的swift Firebase返回,ios,swift,xcode,asynchronous,firebase,Ios,Swift,Xcode,Asynchronous,Firebase,我对swift 2中iOS版Firebase SDK有问题。我正在尝试将图片设置为从Firebase存储下载的图片。当我调用函数时,它返回nil。我认为这是因为Firebase sdk提供的下载任务是异步的,因此当返回状态被称为uid时,由于任务尚未完成,因此没有设置必需的uid。我怎样才能解决这个问题,以便返回正确的图片 override func viewDidLoad() { super.viewDidLoad() imageView.image = downloadProfi

我对swift 2中iOS版Firebase SDK有问题。我正在尝试将图片设置为从Firebase存储下载的图片。当我调用函数时,它返回nil。我认为这是因为Firebase sdk提供的下载任务是异步的,因此当返回状态被称为uid时,由于任务尚未完成,因此没有设置必需的uid。我怎样才能解决这个问题,以便返回正确的图片

override func viewDidLoad() {
   super.viewDidLoad()
   imageView.image = downloadProfilePicFirebase()
}
Firebase下载功能:

func downloadProfilePicFirebase() -> UIImage{

    print("download called")

    //local paths
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentDirectorPath:String = paths[0]
    let imagesDirectoryPath = documentDirectorPath.stringByAppendingString("/profiles")

    var uid = String()


    if let user = FIRAuth.auth()?.currentUser {
        let uid = user.uid

        let storageRef = FIRStorage.storage().referenceForURL("gs://myid.appspot.com")
        let profilePicRef = storageRef.child("/profile_pic.jpg")

        let homeDir: NSURL = NSURL.fileURLWithPath(NSHomeDirectory())
        let fileURL: NSURL = homeDir.URLByAppendingPathComponent("Documents").URLByAppendingPathComponent("profiles").URLByAppendingPathComponent("profile_pic").URLByAppendingPathExtension("jpg")

        // Download to the local filesystem
        let downloadTask = profilePicRef.writeToFile(fileURL) { (URL, error) -> Void in
            if (error != nil) {
                print(error)
            } else {
                // svaed localy now put in ImageView
            }
        }
    }
   return UIImage(contentsOfFile: "\(imagesDirectoryPath)"+"/profile_pic_user_"+uid+".jpg")!
}

正如您所提到的,Firebase是异步的,所以让它驱动应用程序中的数据流

不要尝试从Firebase块返回数据-让该块处理返回的数据,然后在该数据在该块内有效后,移动到下一步

有两种选择:

一个选项是从.writeToFile完成处理程序填充数据

override func viewDidLoad() {
   super.viewDidLoad()
   downloadPic()
}

func downloadPic {
    let download = profilePicRef.writeToFile(localURL) { (URL, error) -> Void in
      if (error != nil) {
        // handle an error
      } else {
        imageView.image = UIImage(...
        //then update your tableview, start a segue, or whatever the next step is
      }
    }
}
第二个选项是向节点添加观察者,完成后,填充imageView

override func viewDidLoad() {
   super.viewDidLoad()

   let download = storageRef.child('your_url').writeToFile(localFile)

   let observer = download.observeStatus(.Success) { (snapshot) -> Void in
     imageView.image = UIImage(...
     //then update your tableview, start a segue, or whatever the next step is
   }
}

参考此项。@Dershowitz 123是的,但返回状态意味着将在完成之前调用。我想在这一点上保留函数。请参见此问题和我参考的答案: