我正在创建一个类似于WhatsApp的聊天应用程序,并尝试实现类似于WhatsApp的通知功能。在WhatsApp中,当您收到通知时,它会将数据存储在某个位置,当您关闭Wi-Fi并进入应用程序时,消息将注入应用程序。这意味着WhatsApp即使应用程序关闭也可以访问通知。
我的方法:我在后台模式下接收通知并将其保存到文件中。因此,如果用户断开与互联网的连接并进入应用程序,则消息仍将在applicationWillAppear上注入。这很完美,但是当您强制关闭应用程序(双击主页并向上滑动应用程序)时,它不起作用。我已经搜索了几乎所有内容,并且说如果您强制关闭应用程序,则后台获取将无法工作。
那么WhatsApp是如何做到的呢?还有其他解决方案吗? 我的解决方案: 从XCode中打开后台获取和远程通知的后台模式。接下来,在application:willFinishLaunchingWithOptions:中添加以下代码。
那么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