Xamarin iOS Local Push-уведомления - PullRequest
       6

Xamarin iOS Local Push-уведомления

0 голосов
/ 05 сентября 2018

Как я могу запланировать локальное (без сервера) PUSH-уведомление (не предупреждение) для запуска из моего приложения? Я просто хочу запланировать уведомление из своего приложения и запустить его в указанное время в центре уведомлений. Я пытался использовать LocalNotifications, но они, кажется, работают, только если приложение открыто, и обновляют значок, только если оно закрыто. Я также не вижу способа отправки push-уведомлений, если вы не используете сервер.

В настоящее время я могу запланировать LocalNotification и получить всплывающее уведомление, но я хотел бы, чтобы это работало, когда приложение закрыто, и вместо предупреждения я хотел бы, чтобы push-уведомление появлялось вверху.

Ответы [ 2 ]

0 голосов
/ 06 сентября 2018

Разрешение на уведомление должно быть запрошено, как только приложение запустится, добавив следующий код к методу FinishedLaunching AppDelegate и установив желаемый тип уведомления (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, приложение может по-разному обрабатывать уведомления, когда оно находится на переднем плане и запускается уведомление. Предоставляя UNUserNotificationCenterDelegate и внедряя 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) => 
        {



        });

    }

При вызове этого метода для emample:

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

Уведомление будет отправлено через 20 секунд, если вы закроете свое приложение.

Я загрузил демо на свой github, вы можете скачать его для справки: Демонстрационная ссылка .

И вы можете получить доступ к ссылке для получения дополнительной информации: Документ MicroSoft

0 голосов
/ 05 сентября 2018

попробуйте, это создаст локальное уведомление через 5 секунд, но если вы хотите повторения, увеличьте время более чем на 60

напишите это в вашем приложении делегат

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 
}

}

...