Perseus
Perseus

Reputation: 1588

Application getting crashed in the NSURLConnection

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.

  1. I am clicking button to post the url
  2. When the button is clcked again(within one/two sec), the URL is not posted (I have written logic).
  3. The URL is posted(For the fist button click) and I didn't received any response till now, now I am trying to click the button again which will post the URL now.

My app getting exactly right here. Is it because I am using the _ReleaseObject(_urlConn); in the connectionDidFinishLoading method ????

Upvotes: 0

Views: 535

Answers (2)

danh
danh

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

Jeffery Thomas
Jeffery Thomas

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

Related Questions