Featured post

iOS Dispatch Groups



Usually in an iOS application we try to feature an app to be able to sync some requests that were not able to be sent due to network failure.

A quick implementation of this is to cache some simple Strings in UserDefaults, or maybe an array of it.
And during app did become active, you can try to run DispatchGroup()

This is just a simple discovery that I have that is quick, easy and readable

Imagine if you have an array of post to send to a request, and you want to get a callback only if all the requests are done so you can notify the user that the offline posts were already sent, and you can cleanup the cache.

let group = DispatchGroup()

for i in 0 ..< n {
    group.enter()
    // This is a sample pseudo code
    // not a running code entirely
    MyNetworkClass.request() { response in
        group.leave()
    }
}

group.notify(queue: .main) {
    print("All requests are done")
}

So with this sample code snippet, you can abstract this into a utility function, to handle the sending of cache items in your app, and do a cleanup once all requests are done

Comments

  1. It regards have an option which would suggest utilizing a stage intended for improvement and upkeep of custom business applications. official statement

    ReplyDelete

Post a Comment