swift Firebase return in asynchron Task

后端 未结 1 559
野的像风
野的像风 2021-01-29 09:44

I have a problem with the Firebase SDK for iOS in swift 2. Im trying to set a picture to a downloaded from the Firebase storage. When I call the function it gives back nil. I th

相关标签:
1条回答
  • 2021-01-29 10:16

    Firebase is asynchronous as you mentioned so let it drive the flow of data within your app.

    Don't try to return data from a Firebase block - let the block handle the returned data and then move to the next step once that data is valid within the block.

    There's a couple of options:

    One option is to populate your data from the .writeToFile completion handler

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

    A second option is add an observer to the node and when that completes, populate your 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
       }
    }
    
    0 讨论(0)
提交回复
热议问题