ios - 远程通知未按预期工作

标签 ios objective-c apple-push-notifications

我正在尝试让我的远程通知正常工作,但我遇到了一些问题。

我正在从我的服务器发送通知,并将 content-available 标志设置为 1,这样我的 didReceiveRemoteNotification 就会被触发,我通过在 didReceiveRemoteNotification 中触发以下方法向用户显示通知:

- (void) showPush:(NSString *)message
{

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

  UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  content.body = message;
  content.sound = [UNNotificationSound defaultSound];

  NSString *identifier = @"UYLLocalNotification";
  UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                        content:content trigger:nil];

  [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Something went wrong: %@",error);
    }
  }];
}

应用处于挂起状态时发送的通知根本不显示,而是在应用打开并再次关闭后显示,如下所示:

-> App is suspended: notification is sent
-> App is opened and in  the foreground: I can see that the notification has been processed
-> App is closed and in the background: notification is being displayed with a banner

对于为什么这不能按预期工作的任何建议,我们将不胜感激。

最佳答案

我认为您需要从一个略有不同的应用委托(delegate)回调中调用 showPush:

- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

此回调说明的文档:

Unlike the application(_:didReceiveRemoteNotification:) method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background.

参见:https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application?language=objc

关于ios - 远程通知未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53178391/

相关文章:

ios - 从 iPhone 4 到 iPhone 5 屏幕尺寸兼容性问题

ios - 创建新的配置文件后推送不起作用?

objective-c - 如何动态确定 Objective-C 属性类型?

ios - 我们可以保存一个特定的 NSManagedObject 吗?

ios - 扩展或自定义 cocoapods 的正确方法

ios - 同步推送通知

ios - 从网络服务器(ASIHTTPRequest、PHP、mysql)更新 iOS TableView 单元格中的数据

ios - Swift 字典的 Swift 数组

ios - 具有关系的 PFObject 子类化

ios - 将 CFAbsoluteTime 存储到 nsmutablearray