In Swift, How to Wait Until a Server Response Is Received Before I Proceed

Swift 3 - Wait for the server result

You can use Closer to acheive this make the following Changes

@IBAction private func bt_signin () {
print("Step 1")
func_a(text: "") { (isSuccess) in
self.func_b()
}
}

private func func_a(text: String , _ completion:@escaping (_ isSuccess:Bool)->Void) {

print("Step 2")

let url = NSURL(string: text)
let request = NSMutableURLRequest(url: url! as URL)

let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
guard error == nil && data != nil else
{
print("Error: ", error)
DispatchQueue.main.async {
completion(false)
}

return
}

let httpStatus = response as? HTTPURLResponse

if httpStatus!.statusCode == 200
{
self.responseCode = httpStatus!.statusCode
DispatchQueue.main.async {
completion(false)
}
print("Step 3")
}
}
task.resume()
}

func func_b (){
print("Step 4")
if (responseCode == 200) {
print("Step 5")
}
}

Wait response before proceeding

Here's an example (based on your code) of how to have myRequest accept a completion block and to call it once the JSON has been deserialized (or not).

public func myRequest(completion: @escaping (_ json: Any?, _ error: Error?)->())
{
var request = URLRequest(url: self.url)
request.httpBody = postString.data(using: .utf8)
let t = URLSession.shared.dataTask(with: request)
{ data, response, error in
guard let data = data,
error == nil else
{
completion(nil, error)
return
}
let json = try? JSONSerialization.jsonObject(with: data, options: [])
//Do other things
completion(json, error)
}
t.resume()
}

And here's how you would call it:

func foo()
{
myRequest()
{ json, error in
// will be called at either completion or at an error.
}
}

Now if you're NOT on main thread, and truly want to wait for your myRequest() to complete, here's how (there are many ways to do this, btw):

func foo()
{
let group = DispatchGroup()
group.enter()

myRequest()
{ json, error in
// will be called at either completion or at an error.
group.leave()
}
group.wait() // blocks current queue so beware!
}

Swift: For Loop Wait Until Response And Return Value According To Response

It's possible to make this synchronous using a DispatchGroup, but this must never be called on the main queue.

// Blocking function. Must not be called on main queue!
func returnFirstKidIsGamer(kidsIds: [String]) -> String? {
let group = DispatchGroup()
var result: String? = nil

for kidID in kidsIds {
// Wait for previous request to finish before trying again.
group.enter()
DataService.instance.isKidAGamer(kidID: kidID) { (isGamer) in
if isGamer {
result = kidId
}
group.leave()
}
group.wait()
guard result == nil else { break }
}
return result
}

This calls group.enter() before entering each loop, and group.leave() when each step completes. It then waits for the step to complete before moving on.

This function is synchronous. It blocks the queue and so must never be called on the main queue. You have to move it to the background with something like this:

DispatchQueue.global(qos: .userInitiated).async {
let kidId = returnFirstKidIsGamer(kidsIds: [kids])
DispatchQueue.main.async {
doSomethingInTheUIWithValue(kidId)
}
}

Note that this returns String?, not String, since no id may be found.

As a rule, you shouldn't do this. You should use a query. But this is how you make asynchronous functions into synchronous functions when needed.

Wait until swift for loop with asynchronous network requests finishes executing

You can use dispatch groups to fire an asynchronous callback when all your requests finish.

Here's an example using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished.

override func viewDidLoad() {
super.viewDidLoad()

let myGroup = DispatchGroup()

for i in 0 ..< 5 {
myGroup.enter()

Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
print("Finished request \(i)")
myGroup.leave()
}
}

myGroup.notify(queue: .main) {
print("Finished all requests.")
}
}

Output

Finished request 1
Finished request 0
Finished request 2
Finished request 3
Finished request 4
Finished all requests.

How to wait for an API request to finish before storing data from function callback?

First you need to call completion when all of your data is loaded. In your case you call completion(tracksArray) before any of the getSavedTracks return.

For this part I suggest you to recursively accumulate tracks by going through all pages. There are multiple better tools to do so but I will give a raw example of it:

class TracksModel {

static func fetchAllPages(completion: @escaping ((_ tracks: [Track]?) -> Void)) {
var offset: Int = 0
let limit: Int = 50
var allTracks: [Track] = []

func appendPage() {
fetchSavedMusicPage(offset: offset, limit: limit) { tracks in
guard let tracks = tracks else {
completion(allTracks) // Most likely an error should be handled here
return
}
if tracks.count < limit {
// This was the last page because we got less than limit (50) tracks
completion(allTracks+tracks)
} else {
// Expecting another page to be loaded
offset += limit // Next page
allTracks += tracks
appendPage() // Recursively call for next page
}
}
}

appendPage() // Load first page

}

private static func fetchSavedMusicPage(offset: Int, limit: Int, completion: @escaping ((_ tracks: [Track]?) -> Void)) {
APICaller.shared.getUsersSavedTracks(limit: limit, offset: offset) { result in
switch result {
case .success(let model):
completion(model)
case .failure(let error):
print(error)
completion(nil) // Error also needs to call a completion
}
}
}

}

I hope comments will clear some things out. But the point being is that I nested an appendPage function which is called recursively until server stops sending data. In the end either an error occurs or the last page returns fewer tracks than provided limit.
Naturally it would be nicer to also forward an error but I did not include it for simplicity.

In any case you can now anywhere TracksModel.fetchAllPages { } and receive all tracks.

When you load and show your data (createSpinnerView) you also need to wait for data to be received before continuing. For instance:

func createSpinnerView() {

let loadViewController = LoadViewController.instantiateFromAppStoryboard(appStoryboard: .OrganizeScreen)
add(asChildViewController: loadViewController)

TracksModel.fetchAllPages { tracks in
DispatchQueue.main.async {
self.tracksArray = tracks
self.remove(asChildViewController: loadViewController)
self.navigateToFilterScreen(tracksArray: tracks)
}
}

}

A few components may have been removed but I hope you see the point. The method should be called on main thread already. But you are unsure what thread the API call returned on. So you need to use DispatchQueue.main.async within the completion closure, not outside of it. And also call to navigate within this closure because this is when things are actually complete.

Adding situation for fixed number of requests

For fixed number of requests you can do all your requests in parallel. You already did that in your code.
The biggest problem is that you can not guarantee that responses will come back in same order than your requests started. For instance if you perform two request A and B it can easily happen due to networking or any other reason that B will return before A. So you need to be a bit more sneaky. Look at the following code:

private func loadPage(pageIndex: Int, perPage: Int, completion: @escaping ((_ items: [Any]?, _ error: Error?) -> Void)) {
// TODO: logic here to return a page from server
completion(nil, nil)
}

func load(maximumNumberOfItems: Int, perPage: Int, completion: @escaping ((_ items: [Any], _ error: Error?) -> Void)) {
let pageStartIndicesToRetrieve: [Int] = {
var startIndex = 0
var toReturn: [Int] = []
while startIndex < maximumNumberOfItems {
toReturn.append(startIndex)
startIndex += perPage
}
return toReturn
}()

guard pageStartIndicesToRetrieve.isEmpty == false else {
// This happens if maximumNumberOfItems == 0
completion([], nil)
return
}

enum Response {
case success(items: [Any])
case failure(error: Error)
}

// Doing requests in parallel
// Note that responses may return in any order time-wise (we can not say that first page will come first, maybe the order will be [2, 1, 5, 3...])

var responses: [Response?] = .init(repeating: nil, count: pageStartIndicesToRetrieve.count) { // Start with all nil
didSet {
// Yes, Swift can do this :D How amazing!
guard responses.contains(where: { $0 == nil }) == false else {
// Still waiting for others to complete
return
}

let aggregatedResponse: (items: [Any], errors: [Error]) = responses.reduce((items: [], errors: [])) { partialResult, response in
switch response {
case .failure(let error): return (partialResult.items, partialResult.errors + [error])
case .success(let items): return (partialResult.items + [items], partialResult.errors)
case .none: return (partialResult.items, partialResult.errors)
}
}

let error: Error? = {
let errors = aggregatedResponse.errors
if errors.isEmpty {
return nil // No error
} else {
// There was an error.
return NSError(domain: "Something more meaningful", code: 500, userInfo: ["all_errors": errors]) // Or whatever you wish. Perhaps just "errors.first!"
}
}()

completion(aggregatedResponse.items, error)
}
}

pageStartIndicesToRetrieve.enumerated().forEach { requestIndex, startIndex in
loadPage(pageIndex: requestIndex, perPage: perPage) { items, error in
responses[requestIndex] = {
if let error = error {
return .failure(error: error)
} else {
return .success(items: items ?? [])
}
}()
}
}

}

The first method is not interesting. It just loads a single page. The second method now collects all the data.

First thing that happens is we calculate all possible requests. We need a start index and per-page. So the pageStartIndicesToRetrieve for case of 145 items using 50 per page will return [0, 50, 100]. (I later found out we only need count 3 in this case but that depends on the API, so let's stick with it). We expect 3 requests starting with item indices [0, 50, 100].

Next we create placeholders for our responses using

var responses: [Response?] = .init(repeating: nil, count: pageStartIndicesToRetrieve.count)

for our example of 145 items and using 50 per page this means it creates an array as [nil, nil, nil]. And when all of the values in this array turn to not-nil then all requests have returned and we can process all of the data. This is done by overriding the setter didSet for a local variable. I hope the content of it speaks for itself.

Now all that is left is to execute all requests at once and fill the array. Everything else should just resolve by itself.

The code is not the easiest and again; there are tools that can make things much easier. But for academical purposes I hope this approach explains what needs to be done to accomplish your task correctly.

Swift - Wait for dataTaskWithRequest response before proceeding

The task completes on a different thread than which it is called, this is by design so network requests don't stop execution on the main thread. So your block of code is sent off async and processResult is called before the network request is finished. You can put the call in the do block or add a closure to the method that can be called.

func remoteRand(completion: (response: Int) ->()) {

// your code
// process JSON
// get value
completion(dataReceived)
// is passed back, just like the dataTaskWithRequest method to your caller where you can set the property on self, etc.
}

using it somewhere:

remoteRand { [weak self] (response) in 
self?.dataResult = response
}

Wait for a network call to complete before returning a value

You need a completion handler if you want to return values from an async operation. dataTaskWithRequest is an async process. Do this:

func sendAPIRequest(endpoint:String, complete: (JSON) -> ())
{
var json = JSON("")
let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
json = JSON(data: data!)
complete(json)
}

}
task.resume()

}

And then call it like so:

sendAPIRequest(<your endpoint string>) { theJSON in
//Use the Json value how u want
}


Related Topics



Leave a reply



Submit