ios – UIApplicationLaunchOptionsRemoteNotificationKey没有获取userinfo

前端之家收集整理的这篇文章主要介绍了ios – UIApplicationLaunchOptionsRemoteNotificationKey没有获取userinfo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我目前的项目中,我有一个推送通知.当我点击应用程序图标时,我想从启动选项对象获取收到的通知,但它总是返回nil:
  1. NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

解决方法

您无法检测到这种情况,因为应用程序未使用推送通知打开(它已通过应用程序图标打开).
尝试通过滑动推送通知打开应用程序.

编辑:

如果您希望调用推送通知(通过后台获取,当您的应用程序未处于活动状态时),您需要让后端开发人员在推送通知中设置“content-available”:1.

之后-application:didReceiveRemoteNotification:fetchCompletionHandler:将被调用(当推送通知到达时),因此您可以将有效负载保存到文件中,然后当应用程序打开时,您可以读取文件并执行操作.

  1. - (void)application:(UIApplication *)application
  2. didReceiveRemoteNotification:(NSDictionary *)userInfo
  3. fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  4. {
  5. NSLog(@"#BACKGROUND FETCH CALLED: %@",userInfo);
  6. // When we get a push,just writing it to file
  7. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  8. NSString *documentsDirectory = [paths objectAtIndex:0];
  9. NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"];
  10.  
  11. [userInfo writeToFile:filePath atomically:YES];
  12. completionHandler(UIBackgroundFetchResultNewData);
  13. }
  14.  
  15. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  16. {
  17. // Checking if application was launched by tapping icon,or push notification
  18. if (!launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
  19. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
  20. NSString *documentsDirectory = [paths objectAtIndex:0];
  21. NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"];
  22.  
  23. [[NSFileManager defaultManager] removeItemAtPath:filePath
  24. error:nil];
  25. NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:filePath];
  26. if (info) {
  27. // Launched by tapping icon
  28. // ... your handling here
  29. }
  30. } else {
  31. NSDictionary *info = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
  32. // Launched with swiping
  33. // ... your handling here
  34. }
  35. return YES;
  36. }

另外,不要忘记在“后台模式”中启用“远程通知

猜你在找的iOS相关文章