Multiple objects waiting for the same API response - ios

I have an API code, which loads a data necessary for my application.
It's as simple as:
- (void) getDataForKey:(NSString*) key onSuccess:(id (^)())completionBlock
I cache data returned from server, so next calls of that functions should not do network request, until there is some data missing for given key, then I need to load it again from server side.
Everything was okey as long as I had one request per screen, but right now I have a case where I need to do that for every cell on one screen.
Problem is my caching doesn't work because before the response comes in from the first one, 5-6 more are created at the same time.
What could be a solution here to not create multiple network request and make other calls waiting for the first one ?

You can try to make a RequestManager class. Use dictionary to cache the requesting request.
If the next request is the same type as first one, don't make a new request but return the first one. If you choose this solution, you need to manager a completionBlock list then you will be able to send result to all requesters.
If the next request is the same type as first one, waiting in another thread until the first one done. Then make a new request, you API will read cache automatically. Your must make sure your codes are thread-safe.
Or you can use operation queues to do this. Some documents:
Apple: Operation Queues
Soheil Azarpour: How To Use NSOperations and NSOperationQueues

May be there will be so many time consuming solutions for this. I have a trick. Create a BOOL in AppDelegate, its default is FALSE. When you receive first response, then set it TRUE. So when you go to other screen and before making request just check value of your BOOL variable in if condition. If its TRUE means response received so go for it otherwise in else don't do anything.

Related

Should I use operation queue for this complete scenario?

I need to perform a scenario with the following steps:
To make a network call with some search parameters provided by the user
Then, to parse its JSON response and create model entities
Then, for each entity created and if it has an associated image URL, to call the corresponding service for downloading such image and to show it in a UICollectionView when download finishes.
I need to handle concurrent network calls when downloading the N images I'd need. User should have the possibility to cancel the current search flow and start a new one. In addition, I should take into account that the cell for a certain image has not been displayed yet or it has been dequeued. So, my question is: which would be the best approach for this?
Perform the first network call (no concurrency) and the JSON response parsing directly using URLSession and URLSessionDownloadTask, and using Operation and OperationQueue for the subsequent steps. Use both invalidateAndCancel() for the URLSession and cancelAllOperations() for the OperationQueue if the user wants to cancel the current search.
Perform the complete process using Operation and OperationQueue.
Any other and more appropriate approach?
The best approach would be to do either a sync or async call to make the first service call. Once completed, parse the json synchronously and then use lazy loading concept (async call) to load if any images are to be downloaded to display the images.
Perform the network call then make the model objects. return these to your VC through your API completion block.
Then reload your collection view and pass the url to each cell and have each cell worry about itself, use something like SDWebImage to show the images async in the cells..

How can I use results of POST call to API to do another POST call

In a project I am working on, I am calling an https API with a POST request which gives me results as a JSON. I am doing the call with AlamoFire, and parsing this with SwiftJSON.
All goes according to plans, and the JSON is received and can be parsed. But now I want to use the values from the received JSON, and immediately do another call to the same API with a different path and use those values as parameters in the call.
At the moment I am posting a NSNotification and when that NSNotification is received I do the POST call to the other path for the details of the data. This works, but not very consistently.
I think that sometimes the data gets in the wrong sequence and the parameters might not be correct. About 80% of the time it works as expected.
Is this the way to work? Or is this not correct to do it with NSNotification? Any insights on this might help!
If you're using this notification pattern correctly, it should work 100% of the time, not 80% of the time. Or, more accurately, if the network connection or server response fails for reasons outside of your control, you should handle it gracefully. If you need help on that problem, update your question with MCVE and we'll see if we can help you.
In terms of a more efficient way to handle this overall process, the typical pattern would be to initiate the second request from inside the response closure of the first request.
Alamofire.request(.POST, url1, parameters: parameters1).response { request, response, data, error in
// create url2 and/or parameters2
Alamofire.request(.POST, url2, parameters: parameters2).response { request, response, data, error in
// do something with second request
}
}
One would generally only use the notification pattern if there is no reliable relationship between the two processes (e.g. when the first request was initiated, it has no reasonable way of possibly knowing which (if any) secondary request(s) will need to react in response to the first request.

Concurrent task in AFNetworking

Currently I am running 3 task concurrently using AFNetworking.But my problem is that I need to refresh tableview once all the above three task complete.But as in AFNetworking all the operation are async. So any operation can finish first. I am not getting a point where I need to refresh my tableview. I am planning to do some critical section type implementation.Is there can other way to accomplish the above.
Use the built-in batched request operation feature of AFNetworking. The completion handler for the batch would include the logic to refresh your data source once all of the operations have finished.
Maybe having some sort of 'active requests array' is a solution for you.
Every time you make a request, add it to the (mutable) array.
When the request finishes, remove it from the array.
Every time a request finishes, check the array length (count).
If your array has become empty again, all request have been finished and you can reload your tableview.

How to avoid calling a method multiple times when the method takes long time to complete

There are several view controllers in my app where I need to sync the local contents with server using a method running in a background thread. Sometimes I need to insert data to my database on server if user has created any. The approach I am using here is to set a flag(something like isSynced = NO) on objects that I need to sync with server (there objects are in Core Data). When the syncing is complete my method will get rid of the flag(e.g. isSynced = YES) so it won't be sent again next time.
Now the problems is that the syncing method takes very long to complete(1 or 2seconds.). If now user pops out this particular view controller and swiftly comes back the previous call is still in progress and next one will be kicked off. The consequence is that there might be duplication in database.
My approach now is the make the syncing method to be called by a Singleton object:
#property (nonatomic) BOOL isSyncing;
//every time before syncing. check if object is available for syncing
if (!isSyncing) {
isSyncing = YES;
// sync server
// when complete
isSyncing = NO;
// post notification to view controller to reload table
} else {
// cancel because previous call is not finished
}
My concern is that if the call is cancelled my view controller will not be able to receive the notification is waiting for. I can fix this by posting another notification in the event of cancelation. I am wondering if this is the right to do this because I think that this problem should be pretty common in iOS development and there should be a standard way to deal with it
Your singleton approach may not be necessary. I don't see the harm in sending a database insert for each new object. You will still need to ensure each object is synched. That is, update the "isSynched" flag. Keep each object that needs to be synced in a "need to synch" list.
Then, update the "isSynced" flag by performing a background query on the database to check if the object exits. Then, use the result of the query to set the isSynched flag.
If the query result indicates the object is not in the database you then resend the object and leave it's "isSynced" flag set to NO.
If the query result indicates the object is in the database, set the "isSynced" flag to YES and remove it from your "need to synch" list.
An approach for preventing duplicate database entries is to make a unique key. For example, tag each with a hash based on the time and date. Then configure the table to ensure each key is unique.

Cancelling NSJSONSerialization - Search as you type, requests overlapping

Similar to the iPhone Facebook app search function, I am implementing search as you type functionality into my application although I have a problem when decoding the data into JSON format.
Basically what happens is because some searches take longer than others, they return at different intervals and this causes some small visual issues when the data is presenting on the screen.
I have set an NSLOG after each decode using NSJSONSerialization for the keyword 'industry'
2013-04-09 23:38:18.941 Project Name [42836:1d03] http://fooWebAddress/json/?method=search&limit=10&q=indus
2013-04-09 23:38:19.776 Project Name [42836:3e07] http://fooWebAddress/json/?method=search&limit=10&q=indu
2013-04-09 23:38:20.352 Project Name [42836:8803] http://fooWebAddress/json/?method=search&limit=10&q=indust
2013-04-09 23:38:21.814 Project Name [42836:4e03] http://fooWebAddress/json/?method=search&limit=10&q=industr
2013-04-09 23:38:23.434 Project Name [42836:8803] http://fooWebAddress/json/?method=search&limit=10&q=ind
2013-04-09 23:38:24.070 Project Name [42836:7503] http://fooWebAddress/json/?method=search&limit=10&q=industry
As you can see it is all out of order.
Does anyone have any way of stopping NSJSONSerialization for the previous connection.
Or possibly any other way to go about this problem?
Steps up to NSJSONSerialization...
NSURLRequest (initwithURL)
NSOperationQueue
NSURLConnection (asynchronous)
NSJSONSerialization
Thanks in advance.
When the user starts typing more text, you could cancel your previous connections and ignore any further delegate callbacks you receive from them. Then make the new request for the current text.
You can do this by maintaining some sort of lastRequest or lastOperation reference. When the user starts typing, call [self.lastRequestOrOperation cancel] and ignore any further notifications from that request with a check like if (request != self.lastRequest) { return; } in whatever callbacks you have.
However this has the problem that if the user keeps typing for a while you are constantly cancelling requests and they may not see any results until they have stopped typing.
A better solution would be to add sequencing so that each request is associated with an increasing sequence ID. You then only parse the result and update the UI when the sequence of the response is higher than the last one you received. If you receive any out-of-band responses from earlier, you just ignore them.
This is a much more complex issue than just being able to cancel the NSJSONSerialization. My suggestion is to use NSFetchedResultsController to populate your table view that shows the search results. Use the search term as one of the predicate variable in the NSFetchRequest attached to NSFetchedResultsController. And then, when you parse the results using NSJSONSerialization, store the results with the search term associated with that request. As soon as the search term changed (which you can detect when the user types more characters), re-create the NSFetchedResultsController and reload your table view. In addition, you can also try to cancel the call to parse the previous results if you launched it using performSelector:withObject:afterDelay. Beware that this cannot be always relied upon as the call may have been initiated by the time you are trying to cancel.
Kinda basic, but you could always maintain an nsdictionary of sub-classed NSURLRequests (sub-classed to provide a tag).
Start request - add request to dicationary with tag = array.count - 1, with key matching tag
Connection returns - is the request the most recent request, if so, parse json
Parse JSON - is the request the most recent request, if so, show results, if not, only display if there are no previous results displayed
Request handling - remove key from dictionary
most recent request = does the dictionary contain an object with a higher key value
Currently what you are doing is, you type each character and calling web-service. Why to call web-service for each letter you type. If user is type continuously, then it will increase the load, so call the web-service only when user stops for a particular interval of time. and then pass that string to call web-service or what ever method you are calling.
[NSObject cancelPerformSelectorsWithTarget:self]; // This will cancel your all req which is going to make when user typing without stopping
[self performSelector:#selector(sendSearchRequest) withObject:searchText afterDelay:0.1f]; // This will pass the string to call a web-service method, on which user hold for some time.

Resources