0

可能重复:
当应用程序不活动时 iOS 后台下载

当应用程序进入后台时,我希望我的 iOS 应用程序代码部分继续运行。

我有一些应该运行函数序列的类。每个函数都使用 ASIHTTPRequest 异步加载数据。我想在应用程序处于后台并且最后一个 ASIHTTP 请求完成时继续运行这些功能,我应该显示本地通知。

我有类似遵循代码的东西

- (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];
}

我尝试使用下一个代码包装每个方法,当应用程序在后台时,最后一个请求函数永远不会完成: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { ..func's scope.. }];

4

1 回答 1

0

您需要为您的 dispatch_async 使用 beginBackgroundTaskWithExpirationHandler,否则当应用程序在后台时它不会运行。

于 2012-06-20T17:05:41.647 回答