I am writing an app that needs to make a number of network API calls (which all complete asynchronously, and wait until they all complete before moving on to the next step in my code. How do I do that?
I need to wait for a bunch of network APIs to complete. How do I do that?
81 Views Asked by Duncan C At
1
There are 1 best solutions below
Related Questions in SWIFT
- Navigate after logged in with webservice
- URLSession requesting JSON array from server not working
- When using onDrag in SwiftUI on Mac how can I detect when the dragged object has been released anywhere?
- Protect OpenAI key using Firebase function
- How to correct error: "Cannot convert value of type 'MyType.Type' to expected argument type 'Binding<MyType>'"?
- How to share metadata of an audio url file to a WhatsApp conversation with friends
- Using @Bindable with a Observable type in SwiftUI
- How to make a scroll view of 9 images in a forEach loop open on image 6 if image 6 is clicked on from a grid?
- Using MTLPixelFormat.rgba16Float results in random round-off errors
- Search and highlight text of current text in PDFKit Swift
- How is passing a function as a parameter related to escaping autoclosure?
- Actionable notification api call not working in background
- Custom layout occupies all horizontal space
- Is it possible to fix slow CKAsset loading on Cloudkit?
- Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value - MapView.isMyLocationEnabled
Related Questions in GRAND-CENTRAL-DISPATCH
- `assumeIsolated(_:)` fails with DispatchSerialQueue as custom Executor in Actor
- What is the expected behavior if I write the same variable on different DispatchQueue?
- Retrieving data via fetching & websocket... into a single data source. Should I use a serial queue to ensure non-garbage data?
- Change completion for async Task which is "in-progress" (Swift Concurrency)?
- Convert code with GCD to async/await in Swift?
- if self in dispatch_source_set_event_handler need to be weak
- How to stop ongoing dispatch group execution and start new one?
- Exit command line Network.framework app that uses dispatch_main()
- Will DispatchQueue.global(qos: .background).async and DispatchQueue.main.async get cancelled when in background or foreground?
- Proper use of strongSelf / weakSelf in nested dispatch_after blocks
- Does a dispatch group block the main thread in iOS?
- What could cause different output for the same code?
- UITableViewCell image from url is wrong at first load
- What is the difference between these DispatchTime calculations?
- I need to wait for a bunch of network APIs to complete. How do I do that?
Related Questions in FOUNDATION
- NSFileManager does not properly work
- NSURLSessionDataTask show loading overlay
- Swift 2 : NSData(contentsOfURL:url) returning nil
- Objective C Primitive Types
- Initializing a Unit from String
- iOS10 + Xcode8 documentDirectory weird behavior
- Using NSProcessInfo from C++
- httpAdditionalHeaders not working on linux
- NSNumberFormatter.numberFromString returns unexpected values
- Issues with redirected URLs involving Swift 3.0.2
- String.init(contentsOfFile:) replacement for Linux?
- String.localizedStringWithFormat returns wrong result
- Converting a hex string into base64 in Swift
- How to Represent Dictionary as NSValue in Swift 3?
- Why there is No constant NSArray Literal and NSDictionary Literal
Related Questions in DISPATCHGROUP
- Why does this code deadlock on ios 15 and up?
- Any idea how to fix group.leave() crash report error in dispatch group ('dispatch_group_leave$VARIANT$mp.cold.1 + 36')?
- Hows does DispatchGroup().leave() function correctly across different threads?
- Swift DispatchGroup notify called before task finish
- Does a dispatch group block the main thread in iOS?
- I need to wait for a bunch of network APIs to complete. How do I do that?
- Multiple threads calling same function Swift/SwiftUI
- dataTask() in a loop: Waiting and breaking
- Why can Objective-C dispatch_group_create() return NULL but not Swift DispatchGroup()?
- What does exclamation in purple mean in Xcode?
- In Swift, how do you loop through a list and hand one item at a time to a function with completion closure?
- dispatch_group_wait is not working in Objective-C
- Nested dispatch queues not firing inner dispatch queue
- DispatchGroup sequential execution problem
- How to use DispatchGroup to update UI only after for-in loop has completed
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
This question comes up a lot (And not just with network calls. There are plenty of other examples where you need to wait until a group of background tasks complete before doing something else.)
Thankfully, there is a nice simple solution built into Apple's GCD (Grand Central Dispatch) framework:
DispatchGroups.A dispatch group is a simple object that lets you track pending tasks on any number of threads, and execute a block of code once they are all completed. Using a DispatchGroup is simple. Assuming you want your tasks to run in the background and you want to be notified when they are completed, you could do something like this:
DispatchGroup. Let's call itdispatchGroupdispatchGroup.enter()to tell the dispatch group to wait for that task to completedispatchGroup.leave()to tell the dispatch group that a task has completed.DispatchGroupnotify functions, passing in the code that you want to be executed when the last pending task completes.One form of
notify()takes a completion closure. The other form takes an object of typeDispatchWorkItem(which is just an object that holds a completion closure.)There are also wait functions that cause the called thread to wait synchronously until all the tasks complete.
Here is some simple code showing how to submit several async tasks that will take an unpredictable amount of time, and run a closure once they are all completed. (For simplicity, this example just submits tasks to a background queue using asyncAfter() and random delay values:
A sample run of that function displays text like this to the console:
The jobs are submitted to a background queue in numeric order. Because each one waits for a random amount of time they are completed in a random order.
The
notify()queues a completion handler to run once the last pending task is completed and callsleave().Note that you have to have at least one pending task running in your dispatch group before you call
notify()or the notify call's closure/DispatchWorkItemfires immediately.