如何使用 xamarin forme pcl 解决方案获取在 iOS 上工作的通知?

Jor*_*cio 3 c# asp.net mobile ios xamarin

I\xc2\xb4m 正在开发一个项目,使用 xamarin 表单进行移植。主要重点是设置计划通知以在 iOS 上运行。我\xc2\xb4ve尝试了一些解决方案,例如xam.Plugins.Notifier和通知框架,但它\xc2\xb4t似乎还没有出现在模拟器上。总结一下,这里\xc2\xb4s是我\xc2\xb4所做的,遵循xamarin教程的指导方针:

\n\n

iOS 通知框架:\n https://developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/

\n\n

AppDelegate.cs

\n\n
\n

使用用户通知;

\n
\n\n
//Request notification permissions from the user.\n        UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {\n            // Handle approval\n        });\n
Run Code Online (Sandbox Code Playgroud)\n\n

便携式解决方案 - MainPage.xaml.cs

\n\n
\n

使用用户通知;

\n
\n\n
        //iOS - Notification Framework (version 10 and above).\n        var content = new UNMutableNotificationContent();\n        content.Title = "test";\n        content.Subtitle = "Notification Subtitle";\n        content.Body = "test 02";\n        content.Badge = 1;\n\n        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);\n\n        var requestID = "123";\n        var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);\n\n        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {\n            if (err != null)\n            {\n                // Do something with error...\n            }\n        });\n
Run Code Online (Sandbox Code Playgroud)\n\n

我\xc2\xb4ve 创建了一个非常简单的测试,只是为了让通知触发,但它\xc2\xb4t 似乎不起作用。有人对缺少什么\xc2\xb4s 或任何其他解决方案有任何想法吗?

\n

Jor*_*cio 5

经过大量研究以及我通过 upwork.com 找到的程序员自由职业者的大量帮助后,我们设法找到了解决方案。事实证明我走在正确的道路上,但由于我\xc2\xb4m是xamarin和c#的新手,所以我遗漏了一些部分。

\n\n

我们必须建立依赖关系才能使其正常工作。I\xc2\xb4m 发布的代码与我的组织风格相结合。但我\xc2\xb4m确信任何人都可以将此代码改编为自己的风格。

\n\n
\n

AppDelegate.cs

\n
\n\n
using Foundation;\nusing UIKit;\nusing UserNotifications; \n\nnamespace MyApp_v1.iOS\n{\n\n[Register("AppDelegate")]\npublic partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate\n{\n\n    public override bool FinishedLaunching(UIApplication app, NSDictionary options)\n    {\n        //Locator.CurrentMutable.RegisterConstant(new IOSCookieStore(), typeof(IPlatformCookieStore)); //IPlatformCookieStore\n\n        global::Xamarin.Forms.Forms.Init();\n\n\n\n\n\n        //Notification framework.\n        //----------------------\n    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, err) => {\n            // Handle approval\n        });\n\n        //Get current notification settings.\n        UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {\n            var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);\n        });\n        UNUserNotificationCenter.Current.Delegate = new AppDelegates.UserNotificationCenterDelegate();\n        //----------------------\n\n\n        LoadApplication(new App());\n\n        return base.FinishedLaunching(app, options);\n    }\n\n\n}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,我们在 iOS 解决方案中创建了一个委托(我放入了一个名为 AppDelegates 的文件夹中)。

\n\n
\n

UserNotificationCenterDelegate.cs

\n
\n\n
using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing UserNotifications;\n\n\nnamespace MyApp _v1.iOS.AppDelegates\n{\npublic class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate\n{\n    #region Constructors\n    public UserNotificationCenterDelegate()\n    {\n    }\n    #endregion\n\n    #region Override Methods\n    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)\n    {\n        // Do something with the notification\n        Console.WriteLine("Active Notification: {0}", notification);\n\n        // Tell system to display the notification anyway or use\n        // `None` to say we have handled the display locally.\n        completionHandler(UNNotificationPresentationOptions.Alert);\n    }\n    #endregion\n}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

接下来,我们创建了对 iOS 解决方案的依赖项(我放入了一个名为 AppDependency 的文件夹)。

\n\n
\n

本地通知.cs

\n
\n\n
using System;\nusing UserNotifications;\nusing MyApp _v1.AppInterfaces;\nusing MyApp _v1.iOS.AppDependencies;\nusing Foundation;\nusing static CoreText.CTFontFeatureAllTypographicFeatures;\n\n[assembly: Xamarin.Forms.Dependency(typeof(LocalNotification))]\nnamespace MyApp _v1.iOS.AppDependencies\n{\npublic class LocalNotification : ILocalNotification\n{\n\n\n    public void ShowNotification(string strNotificationTitle, \n                                string strNotificationSubtitle, \n                                string strNotificationDescription, \n                                string strNotificationIdItem, \n                                string strDateOrInterval, \n                                int intervalType, \n                                string extraParameters)\n    {\n        //intervalType: 1 - set to date | 2 - set to interval\n\n\n        //Object creation.\n        var notificationContent = new UNMutableNotificationContent();\n\n\n        //Set parameters.\n        notificationContent.Title = strNotificationTitle;\n        notificationContent.Subtitle = strNotificationSubtitle;\n        notificationContent.Body = strNotificationDescription;\n        //notificationContent.Badge = 1;\n        notificationContent.Badge = Int32.Parse(strNotificationIdItem);\n        notificationContent.Sound = UNNotificationSound.Default;\n\n\n        //Set date.\n        DateTime notificationContentDate = Convert.ToDateTime(strDateOrInterval);\n\n        NSDateComponents notificationContentNSCDate = new NSDateComponents();\n        notificationContentNSCDate.Year = notificationContentDate.Year;\n        notificationContentNSCDate.Month = notificationContentDate.Month;\n        notificationContentNSCDate.Day = notificationContentDate.Day;\n        notificationContentNSCDate.Hour = notificationContentDate.Hour;\n        notificationContentNSCDate.Minute = notificationContentDate.Minute;\n        notificationContentNSCDate.Second = notificationContentDate.Second;\n        notificationContentNSCDate.Nanosecond = (notificationContentDate.Millisecond * 1000000);\n\n\n        //Set trigger and request.\n        var notificationRequestID = strNotificationIdItem;\n        UNNotificationRequest notificationRequest = null;\n\n        if (intervalType == 1)\n        {\n            var notificationCalenderTrigger = UNCalendarNotificationTrigger.CreateTrigger(notificationContentNSCDate, false);\n\n    notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationCalenderTrigger);\n        }\n        else\n        {\n\n            var notificationIntervalTrigger = UNTimeIntervalNotificationTrigger.CreateTrigger(Int32.Parse(strDateOrInterval), false);\n\n            notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationIntervalTrigger);\n        }\n\n\n        //Add the notification request.\n        UNUserNotificationCenter.Current.AddNotificationRequest(notificationRequest, (err) =>\n        {\n            if (err != null)\n            {\n                System.Diagnostics.Debug.WriteLine("Error : " + err);\n            }\n        });\n    }\n\n}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

接下来,我们在便携式解决方案中创建了界面(我放入了一个名为 AppInterfaces 的文件夹中):

\n\n
\n

ILocalNotification.cs

\n
\n\n
namespace MyApp _v1.AppInterfaces\n{\npublic interface ILocalNotification\n{\n\n    //void ShowNotification(string strTitle, string strDescription, string idNotification, string strURL);\n    void ShowNotification(string strNotificationTitle, \n        string strNotificationSubtitle, \n        string strNotificationDescription, \n        string strNotificationIdItem, \n        string strDateOrInterval, \n        int intervalType, \n        string extraParameters);\n}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

最后,在便携式解决方案 MainPage 上,我调用该方法来创建通知:

\n\n
\n

MainPage.xaml.cs

\n
\n\n
                //var notificationData = (DateTime)strNotificationDate.to;\n                DateTime dateAlarmNotificationSchedule = Convert.ToDateTime(2017-28-02 08:30:00);\n\n\n                //Alarm set.\n                //iOS - Notification Framework (version 10 and above).\n                //DependencyService.Get<ILocalNotification>().ShowNotification(strNotificationTitle, strNotificationDescription, strNotificationIdItem, strNotificationURL);\n                DependencyService.Get<ILocalNotification>().ShowNotification("title example", \n                                                                            "subtitle example", \n                                                                            "description example", \n                                                                            "123", \n                                                                            strAlarmNotificationSchedule, \n                                                                            1, \n                                                                            "");\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望这对某人有帮助,因为我无法在网络上找到任何地方。

\n