iOS:在后台运行部分代码

时间:2012-06-19 12:00:38

标签: iphone ios multithreading asihttprequest grand-central-dispatch

  

可能重复:
  iOS Background downloads when the app is not active

当应用程序输入后台时,我希望我的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.. }];

1 个答案:

答案 0 :(得分:0)

您需要为dispatch_async使用beginBackgroundTaskWithExpirationHandler,否则当应用程序在后台时它将无法运行。