简体   繁体   中英

Swift 2 - How can I run a code after an asynchronous method?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM