在Xamarin.iOS项目中,我正在拦截推送通知,并希望在根据iOS项目中可访问的某些条件(存储的首选项)将其呈现给用户之前对其进行修改。如何将数据从iOS项目传递到Notification Service Extension,以及如何将其传递给Notification Service Extension?或者更准确地说,如何从iOS Notification Service Extension项目的Xamarin.Forms项目访问用户首选项?
我最有兴趣访问使用Xamarin.Essentials存储的用户首选项
这是Notification Service Extension的模板代码:
namespace NotifServiceExtension
{
[Register("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
Action<UNNotificationContent> ContentHandler { get; set; }
UNMutableNotificationContent BestAttemptContent { get; set; }
protected NotificationService(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
ContentHandler = contentHandler;
BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
// Modify the notification content here...
var region = Preferences.Get("region_key", "error"); // I cannot access preferences this way
BestAttemptContent.Title = string.Format("{0}[modified]", BestAttemptContent.Title);
ContentHandler(BestAttemptContent);
}
public override void TimeWillExpire()
{
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
ContentHandler(BestAttemptContent);
}
}
}
答案 0 :(得分:0)
最简单的方法是在Xamarin.Forms App
类上公开一个方法。
在 App.xaml.cs 文件中添加这样的新方法:
public string GetUserRegion()
{
return Preferences.Get("region_key", "error");
}
在您的NotificationService
类中,您可以得到如下所示的区域:
var region = (Xamarin.Forms.Application.Current as App)?.GetUserRegion();