Reputation: 1588
I am trying to post a URL to the server using the Asynchronous type like
_urlConn = [[NSURLConnection alloc] initWithRequest:_urlReq delegate: self];
I getting proper response, and I am handling the response well using the delegate methods such as didRecieveResponse and connectionDidFinishLoading. The flow works fine as of now. I am facing a new problem which I couldn't figure it out clearly.
Lets say I am having a button which will post the same URL.
My app getting exactly right here. Is it because I am using the _ReleaseObject(_urlConn);
in the connectionDidFinishLoading
method ????
Upvotes: 0
Views: 535
Reputation: 62686
I just answered somebody's question here about handling multiple concurrent downloads with the same delegate. (@Jeffery is right - it needs to keep state for each, keyed on the connection object).
Here's how I'd handle your specific example...
- (IBAction)postButtonPressed:(id)sender {
sender.enabled = NO; // no more presses until we are ready again
[UIView animateWithDuration:0.3 animations:^{
sender.alpha = 0.3; // or some effect to make your button appear disabled
}];
NSURLRequest *request = // build your post request here
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// check for error, do whatever you intend with the response
// then re-enable the button
sender.enabled = YES;
[UIView animateWithDuration:0.3 animations:^{sender.alpha=1.0;}];
}];
}
Upvotes: 1
Reputation: 42598
You need to be very careful when working with delegate callbacks.
In this example, a single object is the delegate for two simultaneous NSURLConnection objects. This is a bad idea. Unless you develop a way of associating a specific connection with the appropriate response data object, you will end up mixing response data. In this case you make things worse for yourself by using _urlConn (an iVar i assume) instead of connection (the parameter passed to -connectionDidFinishLoading:
).
To simplify all of this, you need to either not make a new request when an existing request is pending, or you need to cancel the old request before you start a new request.
Upvotes: 1