2010-10-08 45 views
1

我知道Apple支持在後臺模式下運行的應用程序,我想要做的是發送http請求以從服務器獲取數據,然後爲用戶提供一些通知,並且我想要在幾次使用timmer期間重複此操作。我正在使用XCode-3.2.4和Iphone4.1模擬器,它支持後臺運行,但是當我向我的服務器發出http請求時,沒有調用響應函數。任何人都可以幫助我如何做到這一點?請。 這樣的代碼:當應用程序在後臺時無法從服務器獲取響應 - iOS4

- (void)applicationDidEnterBackground:(UIApplication *)application{ 
UIApplication* app = [UIApplication sharedApplication]; 

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
    [app endBackgroundTask:bgTask]; 
    bgTask = UIBackgroundTaskInvalid; 
}]; 
// Start the long-running task and return immediately. 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // Do the work associated with the task. 

    responseData = [[NSMutableData data] retain]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.unpossible.com/misc/lucky_numbers.json"]]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    }); 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
[responseData setLength:0]; 
NSLog(@"%@",@"Server responded"); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[responseData appendData:data]; 
NSLog(@"%@",@"Server transfered data"); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 
NSLog(@"%@",@"Server transfered data"); 
UIApplication* app = [UIApplication sharedApplication]; 
[app endBackgroundTask:bgTask]; 
bgTask = UIBackgroundTaskInvalid; 
} 

回答

2

改爲做同步請求。似乎你只能在後臺使用一個線程。

NSURLResponse *response; 
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
相關問題