0

可能重複:
iOS Background downloads when the app is not active的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.. }];

+0

有關示例代碼,請參閱http://stackoverflow.com/questions/8861390/ios-background-downloads-when-the-app-is-not-active/8861677#8861677 –

+0

檢查此幫助:http:/ /jayprakashdubey.blogspot.in/2014/07/execute-code-in-background.html –

回答

0

您需要使用beginBackgroundTaskWithExpirationHandler用於dispatch_async,否則當應用程序位於後臺時不會運行。

+0

那麼,如果我這樣做,並啓動1分鐘無限計時器來發送這兩個電話?我的應用會在10分鐘內終止嗎? – Slavcho