ios – didReceiveRemoteNotification无法在后台运行

我正在开发一个包含大量遗留代码的大型应用程序.
目前 – 有一个实现:

- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

问题是它仅在应用程序位于前台或用户在应用程序处于后台时点击通知时调用.
我试图实现:

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

但该应用程序的行为相同.
在任何情况下 – 当应用程序在后台时,不会调用此方法.
可能是什么问题呢?

解决方法

实现didReceiveRemoteNotification和didReceiveRemoteNotification:fetchCompletionHandler是正确的方法,但您还需要执行以下操作:

确保注册远程通知,请参阅documentation here

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

    return YES;
}

还要确保编辑Info.plist并选中“启用后台模式”和“远程通知”复选框:

此外,您需要在推送通知有效负载中添加“content-available”:1,否则如果应用程序在后台,则不会被唤醒(请参阅documentation here):

For a push notification to trigger a download operation,the
notification’s payload must include the content-available key with its
value set to 1. When that key is present,the system wakes the app in
the background (or launches it into the background) and calls the app
delegate’s
application:didReceiveRemoteNotification:fetchCompletionHandler:
method. Your implementation of that method should download the
relevant content and integrate it into your app

因此有效载荷至少应如下所示:

{
    aps = {
        "content-available" : 1,sound : ""
    };
}

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...