아삭아삭 iOS 개발

[Swift] Notification 알아보기 & Local Notification 적용 순서 정리 본문

Swift

[Swift] Notification 알아보기 & Local Notification 적용 순서 정리

바닐라머스크 2022. 7. 30. 17:18

 

오늘은 Notification이 무엇인지, 어떤 기능을 하고 어떤 종류가 있는지 알아보고 적용 순서를 알아보겠습니다.

 

나중에 제가 다시 보고 참고하려고 간략히 정리한 내용이라 부족한 점이 있을 수 있습니다ㅎㅎ

정정하거나 추가하고자 하는 내용이 있다면 댓글로 알려주세요~

 


1. Notification

  • User Notification Framework
    - 정의 : (앱 실행 여부와 무관하게) 사용자 기기에 알림을 띄우는 기능을 하는 프레임워크
    - 효과 
       1) 사용자의 앱 재사용률(retention)에 기여함
       2) 앱이 종료된 이후에도 사용자에게 새로운 정보를 전달 할 수 있음
    - 사용자가 알림발송 권한 승인(authorization)을 해야만 Notification 실행 가능
       ▶ 권한 허용 개별적 options : alert, badge, sound
    - 사용자가 해당 알림에 대한 작업 실행시까지 알림이 계속 표기됨
    - 개별 앱에 대한 알림표시 설정은 기기 자체의 '설정'을 통해 선택 가능
    - (Local Notification) 알림을 로컬에서 생성하고 표시할 수도 있고,
       (Remote Notification) 알림을 서버단에서 원격으로 생성해서 표시할 수도 있음

 

  • Local Notification VS. Remote Notification
  Local Notification Remote Notification
알림 전달 방식 (xcode내에 알림 문구가 등록되어 있어서)
앱 내부에서 사용자 기기에 알림을 표시함
(xcode상이 아닌)
서버단에서 사용자 기기에 알림을 전달함

→ Push Notification
알림 발송 시기 일정함 일정하지 않음
알림 발송 내용 비슷한 내용들 다양함
테스트 가능 환경 시뮬레이터 환경에서 테스트 가능 시뮬레이터 환경에서 테스트 불가,
실제 기기에서만 확인 가능
테스트 가능 계정 무료/유료 개발자 계정 모두 가능 유료 개발자 계정에서만 구현 가능
주요 활용 앱 1인 사용 앱에서 자주 사용됨 앱서비스를 운영하는 앱, 홍보관련 내용, sns 앱 등에서 자주 사용됨
ex) D-day, 할일 리스트 알림 등 홍보성 알림, 카카오톡 알림 등

 


2. Local Notification 구현 순서 (+ SeSAC 실습내용 + 필기 + 추가 조사내용)

<실습 순서>

1) (적용할 뷰컨) Notification 담당 객체 가져오기

2) (적용할 뷰컨) Notification 권한 요청 함수 생성

3) (적용할 뷰컨) Notification 발송 함수 생성(컨텐츠, 시기)

4) (적용할 뷰컨) Notification 발송 trigger가 될 곳에 3)번 함수 실행시키기

5) (AppDelegate) Notification 제거 로직 설정

6) (AppDelegate) userNotificationCenter 함수 생성

7) (SceneDelegate) badge 제거 시점 설정

 

1) (적용할 뷰컨) Notification 담당 객체 가져오기

let notificationCenter = UNUserNotificationCenter.current()

 

2) (적용할 뷰컨) Notification 권한 요청 함수 생성
  - alert, badge, sound 옵션들에 대해서 권한을 요청하는 함수를 생성함
  - 실습할 때에는 권한 요청에 대해 사용자가 success, error 두 경우로 나누어서 분기처리를 하였으나,

     보다 다양한 상태값이 존재하며 각각 경우 처리가 가능함
     : notDetermined, denied, authorized, provisional, ephemeral

 

Apple Developer Documentation

 

developer.apple.com

 - 아래 생성한 함수는 viewDidLoad()내에서 실행되도록 해줌
 - 사용자가 특정 기기에서 한 번 허용을 하고 나면, 권한 허용 요청 팝업은 다시 나타나지 않음

   (재설정을 요할 경우, 아이폰 자체 설정에서 변경해야함)

func requestAuthorization() {
        
    let authorizationOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
        
    notificationCenter.requestAuthorization(options: authorizationOptions) { success, error in
            
        if success {
            self.sendNotification()
        }
                    
    }
}

 

3) (적용할 뷰컨) Notification 발송 함수 생성(컨텐츠, 시기)

  - 알림을 보낼 시기를 설정하는 방안으로 여러 가지가 있다.
    1. 시간 간격으로 설정 (60초 이상으로 설정해야 반복 가능)
    2. Calendar로 설정
    3. 위치에 따라 설정
  - identifier 설정
    → 알림 관리는 할 필요가 없는 경우, 필요없음
        ex) 알림 클릭시 단순하게 앱을 켜주는 정보
    → 알림 관리는 할 필요가 있을 경우, 고유한 이름이나 일정한 규칙을 줘서 관리
        마치 userDefaults의 key값처럼 알림들을 구분해주는 값이라고 나는 이해했다.

func sendNotification() {
    
    // 알림 내용 생성
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "굿모닝 title 입니다!"
    notificationContent.subtitle = "굿모닝 subtitle 입니다."
    notificationContent.body = "얼른 일어나 세수양치하고 수업 듣자!"
    notificationContent.badge = 1
        
    // 알림 시기 설정(시간 간격으로 할 경우)
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
       
    // 알림 시기 설정(캘린더로 설정할 경우)
    var dateComponents = DateComponents()
    dateComponents.minute = 30 //매시 30분마다 알림이 온다
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
        
    // 알림 요청 및 identifier 설정
    let request = UNNotificationRequest(identifier: "\(Date())", content: notificationContent, trigger: trigger)
        
    notificationCenter.add(request)
}

 

4) (적용할 뷰컨) Notification 발송이 실행되도록 할 곳에 3)번 함수 실행시키기

  - 실습시간의 경우 단순하게 button을 누르면 notification이 오도록 확인하고자 했다.
    그래서 우선 아래 버튼의 액션 내부에 sendNotification() 함수를  추가함

@IBAction func notificationButtonTapped(_ sender: UIButton) {
    sendNotification()
}

 

5) (AppDelegate) Notification 제거 로직 설정

  - AppDelegate 클래스에 UNUserNotificationCenterDelegate 프로토콜 채택부터 해주어야 함

  - 일반적으로 언제 Notification을 제거해 주어야 할까는 (서비스별) 알림의 유효 기간 설정과 연결해서 생각해볼 수 있다.
    :  didfinishlaunch withoptions / active / foreground 등

 ex) 카카오톡의 경우, 10개 알림이 와있더라도 각각의 채팅방이 다르다면 앱을 실행시키는 것만으로는 10개 noti를 전부 삭제할 수 없음

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
    // 노티 제거
    // removeAll : 이전에 온 것만 지울 경우
    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        
    // removeAllPending : 이전에 온 것, 앞으로 올 것 모두 지울 경우
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        
        
    // delegate 연결
    UNUserNotificationCenter.current().delegate = self 
        
    return true
}

 

6) (AppDelegate) userNotificationCenter 함수 생성

  - iOS 14 이전에는 completionHandler([.alert , .badge, .sound]) 였으나, 그 이후에는 .alert이 .list, .banner로 나뉘어짐

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
    // ios 14 기준 버전별 분기처리해줄 수 있음
    completionHandler([.list, .banner, .badge, .sound])
}

 

7) (SceneDelegate) badge 제거 시점 설정

  - badge는 언제 제거하는 것이 맞을까?

    : 실습하는 앱의 경우, 알림이 발송되는 씬이 활성화 될 때로 설정했다.

func sceneDidBecomeActive(_ scene: UIScene) {
        
    // Badge 제거
    UIApplication.shared.applicationIconBadgeNumber = 0
}

 

 

여기까지 Notification에 대해 알아보고  Local Notification 적용 순서에 대해 정리해보았습니다.

SeSAC 수업 중 아래 3가지 케이스에 대해서도 추가로 공부해보는 것을 추천해주셔서, 관련내용 추가정리시 공유하고자 합니다 :)

 

특정한 Notification 클릭시 특정 화면으로 이동하고 싶다면?

앱 내 특정 화면별, 조건별에 따른 Notification foreground 수신을 원한다면?

(iOS15) Notification 받는 것에 우선순위를 적용하고 싶다면? ex) 집중모드 등