getting data out of a closure that retrieves data from firebase

后端 未结 1 640
别跟我提以往
别跟我提以往 2020-11-29 11:33

I am trying to retrieve data from Firebase and store that data outside of the closure that retrieves that data.

    var stringNames = [String] ()
    ref?.ob         


        
相关标签:
1条回答
  • 2020-11-29 12:19

    That's because when you fetch data from Firebase the call is Asynchronous. What you can do:

    Option 1 - Set your logic inside the closure (Like what you have that print the var inside the closure).

    Option 2 - Define your own closure that going to receive your data like:

    func myMethod(success:([String])->Void){
    
        ref?.observeEventType(.Value, withBlock: { snapshot in
            var newNames: [String] = []
            for item in snapshot.children {
                if let item = item as? FIRDataSnapshot {
                    let postDict = item.value as! [String: String]
                    newNames.append(postDict["name"]!)
                }
            }
            success(newNames)
        })
    }
    

    Option 3 - Use the delegate pattern

    protocol MyDelegate{
         func didFetchData(data:[String])
    }
    
    class MyController : UIViewController, MyDelegate{
    
        func myMethod(success:([String])->Void){
            ref?.observeEventType(.Value, withBlock: { snapshot in
               var newNames: [String] = []
               for item in snapshot.children {
                   if let item = item as? FIRDataSnapshot {
                       let postDict = item.value as! [String: String]
                       newNames.append(postDict["name"]!)
                   }
                }
                self.didFetchData(newNames)
            })
        }
    
        func didFetchData(data:[String]){
            //Do what you want
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题