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

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.

Related

How to handle tile request errors from ol.source.WMTS - Openlayers 3

By using the obvious event handler::
layer.getSource().on('tileloaderror', function (ev) {
console.log(ev);
});
I get an output rather useless, since it doesn't seem to contain any information regarding HTTP Response body/headers etc.
Is there a way to access those kind of information after a failed tile request?
In my implementation, access token must be updated, thus response code is necessary.
If not possible after all, maybe there is a way to create a custom tile load request (maybe implement my own "tileloadfunction" or something).

Multiple objects waiting for the same API response

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.

REST call may results in two different JSON objects. What design pattern should I use?

My web application makes a REST call. If the call is successful, it will return a 'weather' json object. If the call fails, it will return a json error object.
I want to make a class that parses the resulting JSON and returns a Weather object if the call succeeded and an Error Object if the call failed.
I'm thinking of using the Factory pattern but I'm not sure if that's a good approach because the two objects are very different from one another. What is a good way to design this code?
A common approach I use is to have Weather and Error both be Response objects and have a ResponseFactory create them.
I strongly encourage you to use proper HTTP codes when designing your service as they give a more general view of the state and success of each call.
You need first to check the result of the call, and then make a decision on how to handle it, with the possibility of handling all error codes with an error callback that returns an Error JSON object, and a success callback to return a Weather JSON object. You can use the HTTP codes to create a proper response and further subdivide the logic to return more specific errors, if needed.
The use of a Factory pattern seems overkill, specially given that the objects don't relate to each other.
It really depends on the environment you'll be using your API.
As a rule of thumb, rely on the HTTP code - if you get a 404 or a 500 of course you can't come up with a parsed response.
Format your error responses in a consistent way, e.g.
404 { "message" : "Resource not found" }
400 { "message" : "Wrong parameters given" }
So you know how to parse them.
If you get a 200 OKyou know everything was right, and you can parse your response with no problem at all.
Does the Content-Type header vary depending on the type of response?
As some have noted in their answers, the HTTP status code should be used to determine "Was there an error", but just as important is the interpretation of the content type returned.
Hoping the Content-Type header does vary, I would suggest using a registry of parsers, registered by content-type they handle, and then delegate to them to handle understanding how to convert a particular content type into the object you want. In Ruby, since you didn't specify a particular language:
case response.status:
when 200..299
return parsers[response.content_type].parse(response.body)
when 400..499
raise parsers[response.content_type].parse(response.body)
else
raise "Unhandled response status"
Doing so separates the two concerns:
Determining if there was an error
Parsing of content types into classes/types in your application.

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.

Help with facebook multiple requests in IOS

I need to perform a series of FBrequests. Basically it is an array which for each item I have to make a FBrequest.
What I need to know is if it is guaranteed that the order of the requests received by the - (void)request:(FBRequest*)request didLoad:(id)result method is the same of when the requests were made. In other words, in case the order of the requests is: FBrequest_1 -> FBrequest_2, is it guaranteed that the didLoad method will receive the responses as: FBresponse_1 -> FBresopnse_2? Or is it possible that the FBresponse_2 is received before the FBresponse_1?
Thanks in advance!
By default the requests are independent. You can use "batch requests".
Here you can see "Specifying dependencies between operations in the request" section.
You can also initiate FBrequest_2 in the callback of FBrequest_1 (=FBresponse_1). Facebook SDK for iOS calls to FB asynchronously and each request has a callback with a response so just call your second request from that callback to make sure it is done alsready, you also can use the information you get from the response in your second request.
hope this helps

Resources