[英]How can I get notifications to work on iOS, using xamarin forme pcl soluction?
I´m in the middle of developing a project, using xamarin forms portable. 我正在使用xamarin便携式表单开发项目。 The main focus is on setting scheduled notifications to work on iOS.
主要重点是设置计划的通知以在iOS上运行。 I´ve tried some solutions like xam.Plugins.Notifier and notifications framework, but it doesn´t seem to show up on the simulator yet.
我尝试了一些解决方案,例如xam.Plugins.Notifier和通知框架,但它似乎尚未出现在模拟器上。 Summing it up, here´s what I´ve done, following the guidlines on xamarin tutorials:
总结一下,这是我在xamarin教程的指导下所做的事情:
Notification Framework for iOS: https://developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/ iOS通知框架: https : //developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/
AppDelegate.cs AppDelegate.cs
using UserNotifications;
使用用户通知;
//Request notification permissions from the user.
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {
// Handle approval
});
Portable solution - MainPage.xaml.cs 便携式解决方案-MainPage.xaml.cs
using UserNotifications;
使用用户通知;
//iOS - Notification Framework (version 10 and above).
var content = new UNMutableNotificationContent();
content.Title = "test";
content.Subtitle = "Notification Subtitle";
content.Body = "test 02";
content.Badge = 1;
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
var requestID = "123";
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
if (err != null)
{
// Do something with error...
}
});
I´ve created a very simple test, in order just to get the notification to fire, but it doesn´t seem to work. 我创建了一个非常简单的测试,目的只是为了触发通知,但是它似乎没有用。 Anyone got any ideias on what´s missing or any other solution?
任何人都对缺少的东西或其他解决方案有任何想法?
After a lot of research and tons of help with a programmer freelancer, that I found throught upwork.com, we managed to find a solution for it. 经过大量的研究和程序员自由职业者的大量帮助后,我在upwork.com上找到了,我们设法找到了解决方案。 Turns out I was in the right path, but since I´m new to xamarin and c#, there were some parts that I was missing.
原来我走的路是正确的,但是由于我是xamarin和C#的新手,所以我缺少了某些地方。
We had to build a dependency for it to work properly. 我们必须建立一个依赖关系使其正常工作。 The code I´m posting, is integrated with my style of organizing.
我发布的代码与我的组织风格融为一体。 But I´m sure anyone can adapt this code to their own style.
但是我敢肯定,任何人都可以根据自己的风格来修改此代码。
AppDelegate.cs
AppDelegate.cs
using Foundation;
using UIKit;
using UserNotifications;
namespace MyApp_v1.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
//Locator.CurrentMutable.RegisterConstant(new IOSCookieStore(), typeof(IPlatformCookieStore)); //IPlatformCookieStore
global::Xamarin.Forms.Forms.Init();
//Notification framework.
//----------------------
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, err) => {
// Handle approval
});
//Get current notification settings.
UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
UNUserNotificationCenter.Current.Delegate = new AppDelegates.UserNotificationCenterDelegate();
//----------------------
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
Then, we created a delegate in the iOS solution (I put in a folder called AppDelegates). 然后,我们在iOS解决方案中创建了一个委托(我将其放置在名为AppDelegates的文件夹中)。
UserNotificationCenterDelegate.cs
UserNotificationCenterDelegate.cs
using System;
using System.Collections.Generic;
using System.Text;
using UserNotifications;
namespace MyApp _v1.iOS.AppDelegates
{
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
#region Constructors
public UserNotificationCenterDelegate()
{
}
#endregion
#region Override Methods
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine("Active Notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert);
}
#endregion
}
}
Next, we created a dependency on the iOS solution (I put in a folder called AppDependencies). 接下来,我们创建了对iOS解决方案的依赖关系(我将其放在名为AppDependencies的文件夹中)。
LocalNotification.cs
LocalNotification.cs
using System;
using UserNotifications;
using MyApp _v1.AppInterfaces;
using MyApp _v1.iOS.AppDependencies;
using Foundation;
using static CoreText.CTFontFeatureAllTypographicFeatures;
[assembly: Xamarin.Forms.Dependency(typeof(LocalNotification))]
namespace MyApp _v1.iOS.AppDependencies
{
public class LocalNotification : ILocalNotification
{
public void ShowNotification(string strNotificationTitle,
string strNotificationSubtitle,
string strNotificationDescription,
string strNotificationIdItem,
string strDateOrInterval,
int intervalType,
string extraParameters)
{
//intervalType: 1 - set to date | 2 - set to interval
//Object creation.
var notificationContent = new UNMutableNotificationContent();
//Set parameters.
notificationContent.Title = strNotificationTitle;
notificationContent.Subtitle = strNotificationSubtitle;
notificationContent.Body = strNotificationDescription;
//notificationContent.Badge = 1;
notificationContent.Badge = Int32.Parse(strNotificationIdItem);
notificationContent.Sound = UNNotificationSound.Default;
//Set date.
DateTime notificationContentDate = Convert.ToDateTime(strDateOrInterval);
NSDateComponents notificationContentNSCDate = new NSDateComponents();
notificationContentNSCDate.Year = notificationContentDate.Year;
notificationContentNSCDate.Month = notificationContentDate.Month;
notificationContentNSCDate.Day = notificationContentDate.Day;
notificationContentNSCDate.Hour = notificationContentDate.Hour;
notificationContentNSCDate.Minute = notificationContentDate.Minute;
notificationContentNSCDate.Second = notificationContentDate.Second;
notificationContentNSCDate.Nanosecond = (notificationContentDate.Millisecond * 1000000);
//Set trigger and request.
var notificationRequestID = strNotificationIdItem;
UNNotificationRequest notificationRequest = null;
if (intervalType == 1)
{
var notificationCalenderTrigger = UNCalendarNotificationTrigger.CreateTrigger(notificationContentNSCDate, false);
notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationCalenderTrigger);
}
else
{
var notificationIntervalTrigger = UNTimeIntervalNotificationTrigger.CreateTrigger(Int32.Parse(strDateOrInterval), false);
notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationIntervalTrigger);
}
//Add the notification request.
UNUserNotificationCenter.Current.AddNotificationRequest(notificationRequest, (err) =>
{
if (err != null)
{
System.Diagnostics.Debug.WriteLine("Error : " + err);
}
});
}
}
}
Next, we created the interface, in the portable solution (I put in a folder called AppInterfaces): 接下来,我们在便携式解决方案中创建了接口(我将其放置在名为AppInterfaces的文件夹中):
ILocalNotification.cs
ILocalNotification.cs
namespace MyApp _v1.AppInterfaces
{
public interface ILocalNotification
{
//void ShowNotification(string strTitle, string strDescription, string idNotification, string strURL);
void ShowNotification(string strNotificationTitle,
string strNotificationSubtitle,
string strNotificationDescription,
string strNotificationIdItem,
string strDateOrInterval,
int intervalType,
string extraParameters);
}
}
Lastly, on the portable solution MainPage, I call the method to create the notifications: 最后,在便携式解决方案MainPage上,我调用创建通知的方法:
MainPage.xaml.cs
MainPage.xaml.cs
//var notificationData = (DateTime)strNotificationDate.to;
DateTime dateAlarmNotificationSchedule = Convert.ToDateTime(2017-28-02 08:30:00);
//Alarm set.
//iOS - Notification Framework (version 10 and above).
//DependencyService.Get<ILocalNotification>().ShowNotification(strNotificationTitle, strNotificationDescription, strNotificationIdItem, strNotificationURL);
DependencyService.Get<ILocalNotification>().ShowNotification("title example",
"subtitle example",
"description example",
"123",
strAlarmNotificationSchedule,
1,
"");
Hope this helps someone, as I couldn't find anywhere on the web. 希望这对某人有帮助,因为我在网络上找不到任何地方。
Taking a look to this plugin 看看这个插件
It say that 它说
In iOS you must request permission to show local notifications first since it is a user interrupting action. 在iOS中,您必须先请求权限才能显示本地通知,因为这是用户的干扰行为。
// Request Permissions
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// Request Permissions
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
{
// Do something if needed
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);
app.RegisterUserNotificationSettings(notificationSettings);
}
I don't know if it is helpful for you 不知道对您有没有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.