演练-在 Xamarin 中使用本地通知Walkthrough - Using Local Notifications in Xamarin.iOS

本部分介绍如何在 Xamarin iOS 应用程序中使用本地通知。它将演示创建和发布通知的基础知识,该通知将在应用接收到警报时弹出。In this section we'll walk through how to use local notifications in a Xamarin.iOS application. It will demonstrate the basics of creating and publishing a notification that will pop up an alert when received by the app.

重要

本部分中的信息适用于 iOS 9 及更早版本。The information in this section pertains to iOS 9 and prior, it has been left here to support older iOS versions. 对于 iOS 10 及更高版本,请参阅用户通知框架指南,以支持 ios 设备上的本地和远程通知。For iOS 10 and later, please see the User Notification Framework guide for supporting both Local and Remote Notification on an iOS device.

演练Walkthrough

让我们创建一个简单的应用程序,该应用程序将在操作中显示本地通知。Let create a simple application that will show local notifications in action. 此应用程序将在其上有一个按钮。This application will have a single button on it. 单击该按钮时,它将创建一个本地通知。When we click on the button, it will create a local notification. 经过指定的时间段后,会看到通知出现。After the specified time period has elapsed, we will see the notification appear.

  1. 在 Visual Studio for Mac 中,创建一个新的单一查看 iOS 解决方案,并 Notifications调用它。In Visual Studio for Mac, create a new Single View iOS solution and call it Notifications.

  2. 打开 Main.storyboard 文件,然后将一个按钮拖到视图上。Open the Main.storyboard file, and drag a button onto the View. 命名按钮按钮,并为其指定标题 "添加通知"。Name the button button, and give it the title Add Notification. 此时,您可能还需要对按钮设置一些约束You may also want to set some constraints to the button at this point:

  3. 编辑 ViewController 类,并向 ViewDidLoad 方法添加以下事件处理程序:Edit the ViewController class, and add the following event handler to the ViewDidLoad method:

    button.TouchUpInside += (sender, e) =>
    {
        // create the notification
        var notification = new UILocalNotification();
    
        // set the fire date (the date time in which it will fire)
        notification.FireDate = NSDate.FromTimeIntervalSinceNow(60);
    
        // configure the alert
        notification.AlertAction = "View Alert";
        notification.AlertBody = "Your one minute alert has fired!";
    
        // modify the badge
        notification.ApplicationIconBadgeNumber = 1;
    
        // set the sound to be the default sound
        notification.SoundName = UILocalNotification.DefaultSoundName;
    
        // schedule it
        UIApplication.SharedApplication.ScheduleLocalNotification(notification);
    };
    

    此代码将创建一个使用声音的通知,将图标徽章的值设置为1,并向用户显示一条警报。This code will create a notification that uses a sound, sets the value of the icon badge to 1, and displays an alert to the user.

  4. 接下来,编辑 AppDelegate.cs的文件,首先将以下代码添加到 FinishedLaunching 方法。Next edit the file AppDelegate.cs, first add the following code to the FinishedLaunching method. 我们已经检查了设备是否正在运行 iOS 8,如果是这样,我们需要请求用户是否有权接收通知:We have checked to see if the device is running iOS 8, if so we are required to ask for the user's permission to receive notifications:

    if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
        var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes (
            UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null
        );
    
        application.RegisterUserNotificationSettings (notificationSettings);
    }
    
  5. AppDelegate.cs中,添加将在收到通知时调用的以下方法:Still in AppDelegate.cs, add the following method which will be called when a notification is received:

    public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
    {
        // show an alert
        UIAlertController okayAlertController = UIAlertController.Create(notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert);
        okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
    
        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(okayAlertController, true, null);
    
        // reset our badge
        UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
    }
    
  6. 我们需要处理因本地通知而导致通知启动的情况。We need to handle the case where the notification was launched because of a local notification. 编辑 AppDelegateFinishedLaunching 的方法,包括以下代码片段:Edit the method FinishedLaunching in the AppDelegate to include the following snippet of code:

    // check for a notification
    
    if (launchOptions != null)
    {
        // check for a local notification
        if (launchOptions.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey))
        {
            var localNotification = launchOptions[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification;
            if (localNotification != null)
            {
                UIAlertController okayAlertController = UIAlertController.Create(localNotification.AlertAction, localNotification.AlertBody, UIAlertControllerStyle.Alert);
                okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
    
                Window.RootViewController.PresentViewController(okayAlertController, true, null);
    
                // reset our badge
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
            }
        }
    }
    
  7. 最后,运行该应用程序。Finally, run the application. 在 iOS 8 上,系统将提示你允许通知。On iOS 8 you will be prompted to allow notifications. 单击 "确定" ,然后单击 "添加通知" 按钮。Click OK and then click the Add notification button. 短暂停顿后,会看到警报对话框,如以下屏幕截图所示:After a short pause you should see the alert dialog, as shown in the following screenshots:

    ![](local-notifications-in-ios-walkthrough-images/image1.png ""添加通知" 按钮")

总结Summary

本演练演示了如何使用各种 API 在 iOS 中创建和发布通知。This walkthrough showed how to use the various API's for creating and publishing notifications in iOS. 它还演示了如何使用徽章更新应用程序图标,以向用户提供一些特定于应用程序的反馈。It also demonstrated how to update the application icon with a badge to provide some application specific feedback to the user.