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