我对这个话题非常头疼.我正在开发一个需要定期轮询网络服务器的应用程序,以便检查新数据.根据返回的信息,我希望将本地通知推送给用户.
我知道这种方法与Apple描述的方法略有不同,其中远程服务器根据APNS进行工作,推送远程通知.但是,我有很多理由不能考虑这种方法.一个是用户身份验证机制.出于安全原因,远程服务器无法考虑用户凭据.我所能做的就是将登录和获取核心移动到客户端(iPhone).
我注意到Apple提供了一个应用程序唤醒并保持打开Socket连接(即VoIP应用程序)的机会.
所以,我开始以这种方式进行调查.在plist中添加了所需的信息,我能够在我的appDelegate中使用类似的东西"唤醒"我的应用程序:
[[UIApplication sharedApplication] setKeepAliveTimeout:1200 handler:^{
NSLog(@"startingKeepAliveTimeout");
[self contentViewLog:@"startingKeepAliveTimeout"];
MyPushOperation *op = [[MyPushOperation alloc] initWithNotificationFlag:0 andDataSource:nil];
[queue addOperation:op];
[op release];
}];
Run Code Online (Sandbox Code Playgroud)
NSOperation然后使用以下块代码启动后台任务:
#pragma mark SyncRequests
-(void) main {
NSLog(@"startSyncRequest");
[self contentViewLog:@"startSyncRequest"];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"exipiration handler triggered");
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
[self cancel];
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableURLRequest *anURLRequest;
NSURLResponse *outResponse;
NSError *exitError;
NSString *username;
NSString *password;
NSLog(@"FirstLogin");
anURLRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:webserverLogin, username, password]]];
[anURLRequest setHTTPMethod:@"GET"];
[anURLRequest setTimeoutInterval:120.00];
[anURLRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
exitError = nil;
NSData …Run Code Online (Sandbox Code Playgroud) iphone objective-c nsurlconnection nsthread objective-c-blocks
我正面临一个问题,没有任何解决方案(还).在用户按下Home按钮后,我正在使用后台任务处理程序来启动一些数据获取.代码类似于:
-(void)startRequest {
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}];
//..
//Fetch data with NSURLRequest / delegate method
//..
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if ([delegate respondsToSelector:delegateErrorMethod])
[delegate performSelector:delegateErrorMethod];
UIApplication *app = [UIApplication sharedApplication];
if (bgTask != UIBackgroundTaskInvalid) {
dispatch_async(dispatch_get_main_queue(), ^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if([delegate respondsToSelector:delegateMethod])
[delegate performSelector:delegateMethod withObject:self];
UIApplication *app = [UIApplication sharedApplication];
if (bgTask != UIBackgroundTaskInvalid) …Run Code Online (Sandbox Code Playgroud)