.NET MAUI(.NET 8)iOS后台DidReceiveRemoteNotification未触发求助
.NET 8 MAUI iOS 后台APNS通知无点击处理解决方案
针对你遇到的后台无用户点击时无法处理APNS通知的问题,以下是经过验证的解决步骤:
关键前提:APNS负载必须包含content-available字段
iOS只会唤醒后台应用处理**包含content-available: 1**的通知负载,这是触发后台处理的核心条件。你的APNS请求payload需要类似这样:
{ "aps": { "alert": "测试通知", "content-available": 1, "sound": "default" }, "customData": "你的自定义负载" }
如果是静默通知(不需要弹窗),可以去掉alert和sound,但必须保留content-available: 1。
配置iOS后台权限
在Platforms/iOS/Info.plist中添加远程通知的后台模式权限:
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>
这一步确保应用被允许在后台接收并处理远程通知。
自定义MauiUIApplicationDelegate并实现正确的导出方法
在.NET 8 MAUI中,你需要创建自定义的UIApplicationDelegate子类,替代默认的MauiUIApplicationDelegate,并在其中导出正确的通知处理方法,同时设置UNUserNotificationCenter的委托:
- 在
Platforms/iOS文件夹下创建CustomAppDelegate.cs:
using Foundation; using UIKit; using UserNotifications; namespace YourAppNamespace.iOS; [Register("AppDelegate")] public class CustomAppDelegate : MauiUIApplicationDelegate { protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // 设置UNUserNotificationCenter的委托 UNUserNotificationCenter.Current.Delegate = this; return base.FinishedLaunching(app, options); } // 处理后台通知(无用户点击) [Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")] public void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) { // 在这里处理你的通知负载,比如写入数据库、触发本地通知等 ProcessNotificationPayload(userInfo); // 必须调用completionHandler,告知iOS处理完成 completionHandler(UIBackgroundFetchResult.NewData); } // 前台通知处理(已正常工作的方法可保留) [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")] public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler) { // 你的前台通知处理逻辑 completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound); } private void ProcessNotificationPayload(NSDictionary userInfo) { // 解析并处理自定义负载 if (userInfo.TryGetValue(new NSString("aps"), out NSObject apsObj) && apsObj is NSDictionary apsDict) { // 处理aps内容 } if (userInfo.TryGetValue(new NSString("customData"), out NSObject customDataObj)) { string customData = customDataObj.ToString(); // 处理自定义数据 } } }
- 修改
Platforms/iOS/Program.cs,使用自定义的AppDelegate:
using UIKit; namespace YourAppNamespace.iOS; public class Program { static void Main(string[] args) { UIApplication.Main(args, null, typeof(CustomAppDelegate)); } }
测试注意事项
- 必须使用真机测试,iOS模拟器对后台通知的支持有限,无法完全模拟真实环境。
- 确保应用处于后台运行状态(不是被用户手动杀死),被杀死的应用无法被APNS唤醒处理后台通知。
- 检查APNS推送的环境(开发/生产)是否与应用的签名配置一致。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

