Xamarin iOS本地推送通知

问题描述 投票:0回答:2

如何从我的应用程序中调度本地(无服务器)PUSH通知(而不是警报)?我只是想安排来自我的应用程序的通知,并在通知中心的给定时间点火。我曾尝试使用LocalNotifications但它们似乎只在应用程序打开时才有效,并且仅在徽章关闭时才更新徽章。除非您使用服务器,否则我也看不到发送推送通知的方法。

目前我可以安排一个LocalNotification并弹出一个警告,但我希望这可以在应用程序关闭时工作,而不是警报,我想在顶部弹出一个推送通知。

ios xamarin notifications xamarin.ios
2个回答
1
投票

应用程序启动后,应通过将以下代码添加到FinishedLaunchingAppDelegate方法并设置所需的通知类型(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;
    }

iOS 10新增功能,当应用程序位于前台并触发通知时,应用程序可以以不同方式处理通知。通过提供aUNUserNotificationCenterDelegate并实现UserNotificationCentermethod,该应用程序可以接管显示通知的责任。例如:

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();
    }

  }
}

要使用系统创建和注册自定义操作,请使用以下代码:

 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) => 
        {



        });

    }

当您调用此方法时,例如:

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

即使您关闭了应用,也会在20秒后推送通知。

我已将我的演示上传到我的github,您可以下载它以供参考:Demo Link

您可以访问该链接以获取更多信息和详细信息:MicroSoft Document


0
投票

尝试这个它会在5秒后创建一个本地通知,但如果你想重复,那么增加时间超过60

在你的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
}

并在您的视图控制器中

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 
}

}

© www.soinside.com 2019 - 2024. All rights reserved.