在 iOS 中强行关闭应用程序时处理 whatsapp 之类的通知?

Handling notification like whatsapp when application is forcefully close in iOS?

我正在创建一个类似于 whatsapp 的聊天应用程序,并尝试实现类似于 whatsapp 的通知功能。在 whatsapp 中,当您收到通知时,它会将数据存储在某处,当您关闭 wifi 并进入该应用程序时,该消息会注入应用程序中。这意味着即使应用程序关闭,whatsapp 也会以某种方式访问​​通知。

我的方法:我在后台模式下接收通知并将其保存到文件中。因此,如果用户与互联网断开连接并进入应用程序,消息仍会注入 applicationWillAppear。这很完美,但是当你强行关闭你的应用程序时(双击主页并向上滑动应用程序)它不起作用。我几乎搜索了所有内容,它说如果您强行关闭您的应用程序,后台提取将无法工作。

那whatsapp是怎么做到的呢?还有什么其他解决方案?

我的解决方案:

为后台获取和来自 XCode 的远程通知打开后台模式。接下来在 application:willFinishLaunchingWithOptions:

中添加了以下代码
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

在 AppDelegate.m 文件中添加了这个

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler{

  NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);

  if (0 < [paths count]) {
    NSString *documentsDirPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirPath stringByAppendingPathComponent:@"notification.txt"];

    NSString *content = [NSString stringWithFormat:@"%@", userInfo];
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
      // Append text to the end of file
      NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath];
      [fileHandler seekToEndOfFile];
      [fileHandler writeData:data];
      [fileHandler closeFile];
    } else {
      // Create the file and write text to it.
      [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
  }

  handler(UIBackgroundFetchResultNewData);

}

更新:我的通知中确实有以下标志

content-available: 1

后台推送不会传送到用户终止的应用程序。

除非它是 voip 推送,在这种情况下,如果需要,应用程序将由 OS 启动(但是是的,如果您的应用程序向用户提供 voip 功能,您只能使用 voip 推送。 )