Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - What's the best way to iterate over results from an APi, and know when it's finished?

I'm getting data from the FatSecret API. In a nutshell, I have several food IDs I need to get data from, iterating over them to add the calories together. Each one must be a separate call. Since these don't run on the main thread, what's the best way of determining when they are all finished? Currently, I track it with a variable that iterates by one each time a call is finished, but I feel like there may be a better way.

    for thisFoodId in foodIds {

    let endpointURL = <URL WITH FOODID>
    guard let url = URL(string: endpointURL) else {
        return
    }
    let urlRequest = URLRequest(url: url)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let task = session.dataTask(with: urlRequest, completionHandler: {
        (data, response, error) in

        guard error == nil else {
            return
        }
        guard let responseData = data else {
            return
        }

        do {

            guard let thisData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
                return
            }

            let calories = thisData["calories"]
            self.totalCalories += calories
            tracker += 1
            if tracker == foodIds.count {
                // RUN COMPLETION CODE
            }
        }
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use DispatchGroups. It will trigger an async callback block when all your requests are completed.

DispatchGroup:

DispatchGroup allows for aggregate synchronization of work. You can use them to submit multiple different work items and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.

In your code, it would like this:

// ...

// Create the DispatchGroup:

let dispatchGroup = DispatchGroup()

for thisFoodId in foodIds {

    // Enter the DispatchGroup:

    dispatchGroup.enter()

    // ...

    let task = session.dataTask(with: urlRequest, completionHandler: {
        (data, response, error) in

        // ...

        do {

            // ...

            if tracker == foodIds.count {

                // Leave the DispatchGroup

                dispatchGroup.leave()
             }
         }

     })

     // When all your tasks have completed, notify your DispatchGroup to run your work item:

     dispatchGroup.notify(queue: DispatchQueue.main, execute: {

         // All your async requests are finished here, do whatever you want :)

     })

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...