当应用程序处于后台时,无法从服务器获得响应 - iOS 4

时间:2010-10-08 06:37:48

标签: iphone

我知道Apple支持在后台运行的应用程序,我想要做的是发送http请求从服务器获取数据,然后给用户一些通知,我想在几次使用timmer重复此操作。我正在使用XCode-3.2.4和Iphone4.1模拟器,它支持后台运行,但是当我向我的服务器发出http请求时,没有调用响应函数。谁能帮我怎么做?请。 像这样的代码:

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

1 个答案:

答案 0 :(得分:2)

执行同步请求。似乎你只能在后台使用一个帖子。

NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];