简体   繁体   中英

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. The main focus is on setting scheduled notifications to work on 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. Summing it up, here´s what I´ve done, following the guidlines on xamarin tutorials:

Notification Framework for iOS: https://developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/

AppDelegate.cs

using UserNotifications;

//Request notification permissions from the user.
        UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {
            // Handle approval
        });

Portable solution - 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. 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.

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

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).

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).

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):

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.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.

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM