0

Possible Duplicate:
iOS Background downloads when the app is not active

I'd like my part of code of iOS app continue running when app did enter background.

I have some class that should run sequence of functions. Every function load data async using ASIHTTPRequest. I want to keep running these functions when app is in background and when the last ASIHTTP request complete I should to show the local notification.

I have something like follow code

- (void) start //call this method from another class
{
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setCompletionBlock:^{
        NSData *responseData = [request responseData];

        NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
        [xmlParser setDelegate:self];
        [xmlParser parse];
        [xmlParser release];
    }];
    [request startAsynchronous];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //parse xml
    if(all is Ok)
    {
        [self func1];
    }
}

- (void) func1
{
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setCompletionBlock:^{
        [self func2];
    }];
    [request startAsynchronous];
}

- (void) func2
{
    //like func1 
    ....
    [self func3];

}

- (void) func3
{
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setCompletionBlock:^{
        //Handling Local Notifications if app is in background
    }];
    [request startAsynchronous];
}

I tried to wrap every method using next code and when the app is in background the last request function never complete: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { ..func's scope.. }];

Community
  • 1
  • 1
tikhop
  • 2,012
  • 14
  • 32

1 Answers1

0

You need to use beginBackgroundTaskWithExpirationHandler for your dispatch_async, otherwise it won't run when the app is in the background.

JosephH
  • 37,173
  • 19
  • 130
  • 154
  • So, what if i do this and start 1 min infinity timer to send these two calls? Will my app terminate in 10 mins? – Slavcho Aug 01 '13 at 15:22