수색…


소개

로컬 알림을 사용하면 앱을 사용하여 서버를 사용할 필요가없는 콘텐츠를 사용자에게 알릴 수 있습니다.

서버에서 트리거되는 원격 알림과 달리 로컬 알림은 앱 내에서 예약되고 트리거됩니다. 일반적으로 알림은 앱과의 사용자 상호 작용을 향상시키고 사용자가 앱을 열고 상호 작용하도록 유도하거나 유도하도록 유도합니다.

UILocalNotification은 iOS 10에서 사용되지 않습니다. 대신 UserNotifications 프레임 워크를 사용하십시오.

비고

UILocalNotification과 푸시 알림을 혼동하지 마십시오. UILocalNotification은 장치에 의해 트리거되고 예약하면 시스템에 복사됩니다.

모래밭:

로컬 알림 스케줄링

기능 을 사용하려면 로컬 알림 등록을 참조하십시오.

빠른

let notification = UILocalNotification()
notification.alertBody = "Hello, local notifications!"
notification.fireDate = NSDate().dateByAddingTimeInterval(10) // 10 seconds after now
UIApplication.sharedApplication().scheduleLocalNotification(notification)

목표 -C

UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"Hello, local notifications!";
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10]; // 10 seconds after now
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

iOS 시뮬레이터에서 알림을 보려면 ^⌘H (control-command-H)를 입력하여 집으로 ⌘L 다음 ⌘L (command-L)을 입력하여 장치를 잠급니다. 잠시 기다리면 알림이 나타납니다 (이 모양은 "로컬 알림 등록"에 설명 된 알림 유형에 따라 달라질 수 있음).

로컬 알림 배너

앱으로 돌아가려면 알림을 스 와이프합니다 (첫 번째보기 컨트롤러의 viewDidLoad , viewWillAppear , viewDidAppear 등에서 알림을 viewDidAppear 하면 알림이 다시 예약됩니다).

지역 알림 등록

iOS 8

사용자에게 지역 알림을 제공하려면 앱을 기기에 등록해야합니다.

빠른

let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)

목표 -C

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];

처음으로 호출 할 때 경고 메시지가 나타납니다.

로컬 알림 등록 알림

사용자가 선택한 것과 관계없이 알림은 다시 표시되지 않고 변경 사항은 설정의 사용자가 시작해야합니다.

받은 로컬 알림에 대한 응답

중요 :이 대리자 메서드는 전경에서만 호출됩니다.

빠른

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    
}

목표 -C

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
}

이 방법은 일반적으로 UIApplicationDelegate 프로토콜을 준수하는 AppDelegate에서 재정의됩니다.

UUID를 사용하여 로컬 알림 관리

흔히 알림을 관리하고 취소 할 수 있어야 알림을 관리 할 수 ​​있어야합니다.

알림 추적

알림에 UUID (Universally Unique Identifier)를 할당하여 추적 할 수 있습니다.

빠른

let notification = UILocalNotification()
let uuid = NSUUID().uuidString
notification.userInfo = ["UUID": uuid]
UIApplication.shared.scheduleLocalNotification(notification)

목표 -C

UILocalNotification *notification = [[UILocalNotification alloc] init];
NSString *uuid = [[NSUUID UUID] UUIDString];
notification.userInfo = @{ @"UUID": uuid };
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

알림 취소

알림을 취소하려면 먼저 모든 알림 목록을 가져온 다음 일치하는 UUID가있는 알림을 찾습니다. 마지막으로 취소합니다.

빠른

let scheduledNotifications = UIApplication.shared.scheduledLocalNotifications

guard let scheduledNotifications = scheduledNotifications else {
    return
}

for notification in scheduledNotifications where "\(notification.userInfo!["UUID"]!)" == UUID_TO_CANCEL {
    UIApplication.sharedApplication().cancelLocalNotification(notification)
}

목표 -C

NSArray *scheduledNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];

for (UILocalNotification *notification in scheduledNotifications) {
    if ([[notification.userInfo objectForKey:"UUID"] compare: UUID_TO_CANCEL]) {
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
        break;
    }
}

이러한 UUID를 모두 Core Data 또는 Realm에 저장하려고합니다.

현지 알림 즉시 제공

즉시 현지 알림을 표시하려면 다음 번호로 전화하십시오.

스위프트 3

UIApplication.shared.presentLocalNotificationNow(notification)

스위프트 2

UIApplication.sharedApplication().presentLocalNotificationNow(notification)

목표 -C

[[UIApplication sharedApplication] presentLocalNotificationNow:notification];

이 기능을 사용하면 UILocalNotification 객체의 fireDatetimeZone 속성을 설정할 필요가 없습니다.

알림 소리

앱이 생성 한 알림에는 맞춤 소리가 제공 될 수 있습니다. 시스템이 로컬 알림에 대한 경고를 표시하거나 앱 아이콘에 배지를하면 알림 소리를 비활성화하지 않는 한이 소리가 재생됩니다.

기본값은 알림에 사용할 사운드가 재생되지 않음을 의미하는 nil입니다.

맞춤 사운드를 제공하려면 .caf , .wav 또는 .aiff 파일을 앱 번들에 추가하십시오. 30 초보다 오래 지속되는 사운드는 지원되지 않습니다. 이러한 요구 사항을 충족하지 않는 사운드를 제공하면 기본 사운드가 재생됩니다 ( UILocalNotificationDefaultSoundName ).

목표 -C

UILocalNotification *notification = [UILocalNotification new];
notification.soundName = @"nameOfSoundInBundle.wav"; // Use UILocalNotificationDefaultSoundName for the default alert sound

빠른

let notification = UILocalNotification()
notification.soundName = "nameOfSoundInBundle.wav"

Swift 3.0 (iOS 10)에서 지역 알림 등록 및 예약

기재

AppDelegate에서

import UserNotifications

didFinishLaunchingWithOptions 메소드에서,

UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in

// Here you can check Request is Granted or not.

}

알림을 작성하고 예약하십시오.

    let content = UNMutableNotificationContent()
    content.title = "10 Second Notification Demo"
    content.subtitle = "From Wolverine"
    content.body = "Notification after 10 seconds - Your pizza is Ready!!"
    content.categoryIdentifier = "myNotificationCategory"

    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 10.0,
        repeats: false)
    
    let request = UNNotificationRequest(
        identifier: "10.second.message",
        content: content,
        trigger: trigger
    )
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

이 코드 부분이 트리거 된 곳에서 알림 권한을 허용 한 경우 알림을 받게됩니다.

제대로 테스트하려면 백그라운드 모드에서 응용 프로그램을 확인하십시오.

iOS10을 사용한 UILocalNotification의 새로운 기능

UILocalNotification 을 사용할 수 있습니다. 이전 API는 UILocalNotification 에서도 잘 작동하지만 대신 사용자 알림 프레임 워크에서 API를 사용하는 것이 좋습니다. 또한 iOS10 사용자 알림 프레임 워크에서만 사용할 수있는 몇 가지 새로운 기능이 있습니다.

자세한 내용은 여기 에서 원격 알림을 참조하십시오. 여기 .

새로운 기능 :

  1. 이제 앱이 iOS 10을 사용하여 전경에있을 때 알림, 소리 또는 배지를 추가 할 수 있습니다.
  2. 이제는 앱이 이미 종료 된 경우에도 사용자가 작업 버튼을 탭 (또는 슬라이딩)했을 때 모든 이벤트를 한 곳에서 처리 할 수 ​​있습니다.
  3. 슬라이딩 제스처 대신 3D 터치 지원.
  4. 이제 하나의 행 코드만으로 특정 로컬 알림을 제거 할 수 있습니다.
  5. 사용자 정의 UI로 풍부한 알림을 지원합니다.

UILocalNotification API를 iOS10 User Notifications 프레임 워크 API로 변환하는 것은 정말 쉽습니다. 그것들은 실제로 비슷합니다.

새 API와 이전 API를 동시에 사용하는 방법을 보여주기 위해 데모를 작성했습니다. iOS10AdaptationTips .

예를 들어,

신속한 구현 :

  1. 가져 오기 사용자 알림
    ///    Notification become independent from UIKit
    import UserNotifications
  1. localNotification에 대한 승인 요청

        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    
  1. schedule localNotification

  2. 응용 프로그램 아이콘 배지 번호 업데이트

    @IBAction  func triggerNotification(){
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil)
        content.sound = UNNotificationSound.default()
        content.badge = UIApplication.shared().applicationIconBadgeNumber + 1;
        content.categoryIdentifier = "com.elonchan.localNotification"
        // Deliver the notification in five seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        // Schedule the notification.
        let center = UNUserNotificationCenter.current()
        center.add(request)
    }
    
    @IBAction func stopNotification(_ sender: AnyObject) {
        let center = UNUserNotificationCenter.current()
        center.removeAllPendingNotificationRequests()
        // or you can remove specifical notification:
        // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"])
    }
    

목표 -C 구현 :

  1. 가져 오기 사용자 알림
    // Notifications are independent from UIKit
    #import <UserNotifications/UserNotifications.h>
  1. localNotification에 대한 승인 요청

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];
    
  1. schedule localNotification

  2. 응용 프로그램 아이콘 배지 번호 업데이트

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:"
                                                        arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!"
                                                       arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)];
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                triggerWithTimeInterval:5.f
                                                repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                        content:content
                                                                        trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"add NotificationRequest succeeded!");
        }
    }];
    

자세한 정보는 여기를 참조하십시오 : iOS10AdaptationTips .

#updated

'NSInternalInconsistencyException'이라는 캐치되지 않은 예외로 인해 앱 종료 중, 이유 : '반복하는 경우 시간 간격이 60 이상이어야합니다.'

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow