0

I am using the following asynchronous method to get data from Firebase, ref is just my database url. It's working perfectly but I want to run the for loop after the data has been loaded. Because it's an asynchronies method, it starts to get the data from the database and immediately goes to the for loop. Anyway I can get it to wait till the data is downloaded then run the for loop? Please help! :-)

 ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
        print(snapshot.value.objectForKey("Table")!)
        s = snapshot.value.objectForKey("items:")! as! String

        Str = s.componentsSeparatedByString(",")


    })

    for(var i = 0 ; i < Str.count ; i++){
        print(Str[i])
    }
anasganim
  • 17
  • 1
  • 5
  • I haven't used Firebase so I'm not 100% sure, but assuming that withBlock is a completion handler, can't you just add the loop at the end of that? – Robert Feb 15 '16 at 21:09
  • Thanks, @Robert ! I tried doing this like you said: ref.observeSingleEventOfType(.Value, withBlock: { snapshot in print(snapshot.value.objectForKey("Table")!) s = snapshot.value.objectForKey("items:")! as! String Str = s.componentsSeparatedByString(",") }, withAnotherBlock: { for(var i = 0 ; i < Str.count ; i++){ print(Str[i]) } }) And I got an Xcode error saying Type of expression is ambiguous without more context. Any other way, please? :-) – anasganim Feb 15 '16 at 21:22
  • Add the for loop inside your completion closure at the bottom where Str = s.componentsSeperatedByString(","). This will allow you to print out the contents of the data returned if it is a String. – darren102 Feb 15 '16 at 21:22
  • First hit when I paste your title into Google: http://stackoverflow.com/questions/30133490/run-code-only-after-asynchronous-function-finishes-executing – Frank van Puffelen Feb 15 '16 at 21:26
  • @darren102, I know that it will work this way, but I want to just get the data then process it outside the closure. Any other idea? – anasganim Feb 15 '16 at 21:27
  • Why do you want to process it outside the closure? The closure is basically what tells you the data is finished; you really have to put your processing in it! – Robert Feb 15 '16 at 21:30
  • Thank you everyone! I think I am just going to have to put everything in the closure or just put the processing in a method and call it from the closure so it's called after the data is processed. Special thanks to @Robert! – anasganim Feb 15 '16 at 21:41

1 Answers1

1

Your code should probably look something like this:

ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
    print(snapshot.value.objectForKey("Table")!)
    s = snapshot.value.objectForKey("items:")! as! String

    Str = s.componentsSeparatedByString(",")

    for part in Str {
        print(part)
    }
})

I also changed your loop to make it compatible with the next version of Swift.

Robert
  • 5,735
  • 3
  • 40
  • 53