我已经在我的 Xamarin.IOS 应用程序中实现了聊天功能,因为无法从服务器端发送远程通知,我使用本地通知来提醒用户新的传入消息。在模拟器中一切正常,我可以看到通知显示在前台和后台模式中。
但是当我在设备上运行应用程序时,通知仅在前台模式下工作。当应用程序在后台时,不会显示通知。
在调查了这个问题后,我发现当应用程序在调试模式下运行时它们工作正常(即从 VisualStudio 启动并且电缆仍然连接)。但是一旦我断开电缆,它们就不会再显示了。
我发现了一些帖子https://stackoverflow.com/a/35029847这表明这一行可以解决问题,但由于处理程序不能再为空,它不会起作用。
application.BeginBackgroundTask("showNotification", expirationHandler: null);
所以我在我的应用程序委托中实现了以下代码,但它仍然无法正常工作
nint taskID = 111;
taskID = application.BeginBackgroundTask("showNotification", expirationHandler: ()=> {
UIApplication.SharedApplication.EndBackgroundTask(taskID);
});
我还尝试了 Background fetch 并在 AppDelegate 的行下方添加,但它不起作用。 application.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);
安排本地通知代码
var content = new UNMutableNotificationContent();
content.Body = body;
content.Sound = UNNotificationSound.Default;
content.UserInfo = dict;
content.Badge = IOSAppConstant.LocalNotificationCount + 1;
var request = UNNotificationRequest.FromIdentifier(chatID, content, null);
// schedule it
UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) =>
{
if (error != null)
{
Console.WriteLine($"Error: {error.LocalizedDescription ?? ""}");
}
else
{
Console.WriteLine("Scheduled...");
}
});
//注册通知
UNUserNotificationCenter.Current.RequestAuthorization
(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
(granted, error) =>
{
if (granted)
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
});
//分配委托
this._userNotificationCenterDelegate = new UserNotificationCenterDelegate();
UNUserNotificationCenter.Current.Delegate = this._userNotificationCenterDelegate;
//通知委托
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
public override void WillPresentNotification(UNUserNotificationCenter center,
UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
completionHandler(UNNotificationPresentationOptions.Alert);
}
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center,
UNNotificationResponse response, Action completionHandler)
{
completionHandler();
}
}
我也尝试在我的聊天控制器上从 BeginBackgroundTask 调用调度通知功能,但它不起作用
该问题类似于本地推送通知在 Xamarin iOS 中不起作用,但没有可用的解决方案。