연습 - Xamarin.iOS에서 로컬 알림 사용

이 섹션에서는 Xamarin.iOS 애플리케이션에서 로컬 알림을 사용하는 방법을 안내합니다. 앱에서 수신할 때 경고를 팝업하는 알림을 만들고 게시하는 기본 사항을 보여 줍니다.

Important

이 섹션의 정보는 iOS 9 이전 버전과 관련이 있으며 이전 iOS 버전을 지원하기 위해 여기에 남아 있습니다. iOS 10 이상의 경우 iOS 디바이스에서 로컬 및 원격 알림을 모두 지원하는 사용자 알림 프레임워크 가이드 를 참조하세요.

연습

작동 중인 로컬 알림을 표시하는 간단한 애플리케이션을 만들 수 있습니다. 이 애플리케이션에는 단일 단추가 있습니다. 단추를 클릭하면 로컬 알림이 생성됩니다. 지정된 기간이 경과하면 알림이 표시됩니다.

  1. Mac용 Visual Studio 새 단일 보기 iOS 솔루션을 만들고 호출합니다Notifications.

  2. Main.storyboard 파일을 열고 단추를 보기로 끕니다. 단추 단추의 이름을 지정하고 제목 에 알림 추가를 지정합니다. 이 시점에서 단추에 대한 몇 가지 제약 조건을 설정할 수도 있습니다. Setting some constraints on the button

  3. 클래스를 ViewController 편집하고 ViewDidLoad 메서드에 다음 이벤트 처리기를 추가합니다.

    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로 설정하고, 사용자에게 경고를 표시합니다.

  4. 그런 다음 파일을 AppDelegate.cs편집하고 먼저 메서드에 다음 코드를 FinishedLaunching 추가합니다. 디바이스가 iOS 8을 실행하고 있는지 확인하기 위해 검사. 그렇다면 알림을 받을 수 있는 사용자의 권한을 요청해야 합니다.

    if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
        var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes (
            UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null
        );
    
        application.RegisterUserNotificationSettings (notificationSettings);
    }
    
  5. 여전히 알림 AppDelegate.cs이 수신될 때 호출되는 다음 메서드를 추가합니다.

    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. 로컬 알림으로 인해 알림이 시작된 경우를 처리해야 합니다. 다음 코드 조각을 포함하도록 메서드 FinishedLaunchingAppDelegate 를 편집합니다.

    // 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. 마지막으로 애플리케이션을 실행합니다. iOS 8에서는 알림을 허용하라는 메시지가 표시됩니다. 확인을 클릭한 다음 알림 추가 단추를 클릭합니다. 잠시 후 다음 스크린샷과 같이 경고 대화 상자가 표시됩니다.

    Confirming the ability to send notificationsThe Add Notification buttonThe notification alert dialog

요약

이 연습에서는 다양한 API를 사용하여 iOS에서 알림을 만들고 게시하는 방법을 보여 줍니다. 또한 사용자에게 애플리케이션 관련 피드백을 제공하기 위해 배지로 애플리케이션 아이콘을 업데이트하는 방법도 설명했습니다.