【发布时间】:2020-10-23 00:52:09
【问题描述】:
我已经在我的 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);
});
我也尝试了后台获取并添加到 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 调用调度通知功能,但它不起作用
问题类似于Local Push notification not working in Xamarin iOS,但没有可用的解决方案。
【问题讨论】:
-
可以从 service 发送通知。检查docs.microsoft.com/en-us/xamarin/ios/platform/… 或者你可以使用azure.microsoft.com/en-us/services/notification-hubs。
-
我知道推送通知是如何工作的,我已经在我的应用程序中实现了它。但是我使用的框架没有推送通知功能。回到这个问题,我看到这个解决方案被推荐得最多。 application.BeginBackgroundTask("showNotification", expirationHandler: null);您知道如何在 IOS13 中进行这项工作吗?
-
@semeinc 我面临同样的问题。在模拟器上或调试时工作正常。但是,不在生活模式下的真实设备上。你找到解决这个问题的方法了吗?
标签: xamarin.ios notifications localnotification unusernotificationcenter ios-background-mode