Search code examples
objective-cconnectionnsmutableurlrequest

Cancel NSURLConnection Objective-C


I have a tableviewapplication, wich when the user select one view it needs to parse some XML to display information.But sometimes the XML is not finished downloading and the user can press the button to select the other view,generating a crash.I think i need to cancel the connection or something to dont cause any conflitct with the new connection,but i dont know exactly how,it suppose to be in ViewWillDisappear correct? Heres how i start the connection on ViewDidAppear:

NSMutableURLRequest * req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://Adress"]
                                                        cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

conn = [NSURLConnection connectionWithRequest:req delegate:self];

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

if(conn)
{
    receivedData = [[NSMutableData alloc]init];
    [DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading..."];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if(conn) [conn cancel];
}

Solution

  • You can call NSURLConnection's cancel method and it will prevent your connections delegate from being called with any more data. You could do this in viewWillDisappear if that's when it makes sense given how your app works.