Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 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 Answer

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 :)

     })

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...