Question

I need to cancel a NSMutableRequest and a XMLParsing if the user choose another view

I do this on ViewDidLoad:

NSMutableURLRequest * req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:endereco]
                                                        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:@"Obtendo Lista..."];
}

I know i have to : [conn cancel]; on viewWillDisappear, but how i can check i the connection is ocurring so i can cancel it? And the same happens to the parse method :

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSXMLParser * parser = [[NSXMLParser alloc]initWithData:receivedData];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
    [receivedData release];
}
Was it helpful?

Solution

You can achieve this by using two flags(BOOL variables). One flag will keep track of connection activity(whether connection is still in progress or has finishedLoading).

So, for connection (BOOL isConnectionActive) set isConnectionActive = YES in viewDidLoad and set it isConnectionActive = NO in connectionDidFinishLoading or connectionDidFailWithError delegate methods. and check

if(isConnectionActive)
{
if(con != nil)
{
 [con cancel];
}
  isConnectionActive=NO;
}

in viewWillApear: method.

similar thing you can do for xmlParsing. you will set isParsingCompleted=NO - (void)parserDidStartDocument:(NSXMLParser *)parser method. and isParsingCompleted=YES

- (void)parserDidEndDocument:(NSXMLParser *)parser;

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;

methods and you will use

if(!isParsingCompleted)
{
if (parser!= nil)
{
   [parser abortParsing];
}
 isParsingCompleted=YES;
}

in viewWillApear: method.[for this you will need a class level reference for parser.]

Thanks,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top