Xamarin iOS Local Push Notifications

2019-08-28 21:07发布

问题:

How can I schedule a local (no server) PUSH notification (not an alert) to fire from my app? I simply want to schedule a notification from my app and have it fire at the given time in the notification center. I have tried to use LocalNotifications but they only seem to work if the app is open, and only update the badge if it is closed. I also see no way of sending push notifications unless you use a server.

Currently I can schedule a LocalNotification and have an alert pop up, but I would like this to work when the app is closed, and instead of an alert, I would like a push notification that pops up at the top.

回答1:

Notification permission should be requested as soon as the app launches by adding the following code to the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions):

...
using UserNotifications;
...



 public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
   {
       ....

        //after iOS 10
        if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
        {
            UNUserNotificationCenter center = UNUserNotificationCenter.Current;

            center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
                 {

                 });

            center.Delegate = new NotificationDelegate();
        }

        else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {

            var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);

        }

        return true;
    }

New to iOS 10, an app can handle Notifications differently when it is in the foreground and a Notification is triggered. By providing aUNUserNotificationCenterDelegate and implementing theUserNotificationCentermethod, the app can take over responsibility for displaying the Notification. For example:

using System;
using ObjCRuntime;
using UserNotifications;


namespace workplat
{
 public class NotificationDelegate:UNUserNotificationCenterDelegate
   {
    public NotificationDelegate()
    {
    }

    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|UNNotificationPresentationOptions.Sound);
    }


    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        // Take action based on Action ID
        switch (response.ActionIdentifier)
        {
            case "reply":
                // Do something
                break;
            default:
                // Take action based on identifier
                if (response.IsDefaultAction)
                {
                    // Handle default action...
                }
                else if (response.IsDismissAction)
                {
                    // Handle dismiss action
                }
                break;
        }

        // Inform caller it has been handled
        completionHandler();
    }

  }
}

To create and register a Custom Action with the system, use the following code:

 public void RegisterNotification(long time)
    {
        UNUserNotificationCenter center = UNUserNotificationCenter.Current;

        //creat a UNMutableNotificationContent which contains your notification content
        UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();

        notificationContent.Title = "xxx";
        notificationContent.Body= "xxxx";

        notificationContent.Sound = UNNotificationSound.Default;

        UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(time, false);

        UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);


        center.AddNotificationRequest(request,(NSError obj) => 
        {



        });

    }

When you call this method ,for emample:

RegisterNotification(20);//set the time you want to push notification

The notification will been pushed after 20 seconds,enen if you close your app.

I have upload my demo to my github, you can download it for your reference: Demo Link .

And you can access the link for more information and details: MicroSoft Document



回答2:

try this it will create a local notification after 5 second but if you want repetitive then increase the time more then 60

write this in your app delegate

import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {

    var window: UIWindow?
//user notification method

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert,.sound])
}
//response to user notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.notification.request.identifier == "testidentifire"
    {
        print("test")
    }
    completionHandler()
}




func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().delegate = self

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
        print("granted\(granted)")
    }
    return true
}

and in your view controller

import UIKit
import UserNotifications

class ViewController: UIViewController,UNUserNotificationCenterDelegate {
override func viewDidLoad() {

    super.viewDidLoad()
//sendign local notification you need three object a contant,trigger,represh
let content = UNMutableNotificationContent()
content.title = "test notifaction"
content.body = "test notification after 5 second"
content.sound = UNNotificationSound.default()

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
let request  = UNNotificationRequest(identifier: "testidentifire", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
    print("error\(error )")
    //this will show notification when app is in background but if you need to show notification on foreground then u need to implement the delegate method of UNuserNotificationcenter.curent in app delegate 
}

}