Reputation: 1106
OK i have tried a lot of different methods for this. I want to call a JSON API,get its response, save the key values, then call it again with different parameters. Most recently, I tried calling the URL method in a for loop, posting an NSNotification in connectionDidFinishLoading:
and NSLogging values in observer when the notification gets posted. But its only logging the values of the final call multiple times.
I use this for the connection initialisation...
eventConnection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self startImmediately:NO];
[eventConnection scheduleInRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[eventConnection start];
This is the delegate method...
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSNotification *eventNotification=[NSNotification notificationWithName:@"eventsFound" object:nil userInfo:responseDict];
[[NSNotificationQueue defaultQueue]enqueueNotification:eventNotification postingStyle:NSPostNow coalesceMask:NSNotificationCoalescingOnName forModes:nil];
}
Any suggestions as to how i can achieve this?
Upvotes: 0
Views: 2164
Reputation: 2285
You can use NSOPerationQueue or Block or thread for same. Call another function after finishing one.
Upvotes: 0
Reputation: 146
Hum,
Did you try to use Libraries like AFNetworking, you can create asynch request and using blocks to handle answers.
Upvotes: 0
Reputation: 8947
set a counter and total number of requests to send. and in connection did finished loading, check that if counter is reached to total number of rquests to send else call the method again in which you was sending the data, and increment sent requests. if u use data from file. i.e. first write data to file wid a number and then read it when u want to send request, then it wud b great
Upvotes: 2
Reputation: 69047
To effectively chain multiple NSURLConnection requests, you should not start them all at once (e.g., like you say "in a for loop").
Instead, start the first request; then, from the connectionDidFinishLoading
start the second; then again, when connectionDidFinishLoading
is executed again, start the third and so on.
This is just a sketch of how you could do it to help you find a good design for your app; one possibility is:
define a state machine that is responsible for firing the requests depending on the current state; (the state could be a simple integer representing the sequential step you have go to);
start the state machine: it will fire the first request;
when the request is done, connectionDidFinishLoading
will signal the state machine, so that it moves to the next step;
at each step, the state machine fires the request corresponding to that step.
There are other design options possible, of course; which is the best will depend on your overall requirements and the kind of call flow you need.
Upvotes: 3