后台获取和本地通知

Background Fetch and Local Notification

在我的应用程序中,我打算使用本地通知而不是推送通知。我需要检查事务更新是否可用,如果是,只需使用本地通知通知用户。我已经完成了以下步骤。

  1. didFinishLaunchingWithOptions中,设置获取间隔[[UIApplication sharedApplication]setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]
  2. -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

> 添加了 POST 请求的代码,如下所示以及我的请求数据:

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

if(conn) {
    completionHandler(UIBackgroundFetchResultNewData);
}
 else {
    completionHandler(UIBackgroundFetchResultFailed);
}
  1. 响应解析后,比较是否有更新,如果有更新,使用以下代码显示通知。

    UILocalNotification* localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.alertTitle = @"SIB Mirror";
    localNotification.alertBody = @"You have a new transaction. Go to e-Statements to view it.";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    

问题是大多数时候,当 phone 被锁定时,收到错误消息 >Error Domain=NSURLErrorDomain Code=-1005 “网络连接丢失。”

因此没有显示通知。但是当我将 Phone 直接连接到 Phone 并在调试模式下启用后台同步时,一切正常。

请指导我一个简单的方法来做到这一点,或者如果我做错了什么,请纠正我。

谢谢,

移动开发人员。

你的这部分代码

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

if(conn) {
    completionHandler(UIBackgroundFetchResultNewData);
}
else {
    completionHandler(UIBackgroundFetchResultFailed);
}

就是说,为我创建一个连接以获取一些数据,并且无论创建此实例会发生什么,都可以完成后台处理。所以 iOS 按照您的要求停止应用程序。

如果无法创建连接,则完成并失败,当然。但是,如果连接已创建,则在您有要处理的响应(数据或错误)之前,您不应该调用完成...

Try POST Request with completion handler.

试试下面的代码:

NSURLResponse * response = nil;
            NSError * error = nil;
            NSData * data = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&error];

if (error == nil)
{
 // Parse data here
  completionHandler(UIBackgroundFetchResultNewData);
}
else {
  completionHandler(UIBackgroundFetchResultFailed);

}