본문 바로가기
iOS_Swift 앱개발👍

[iOS_Swift] 로컬 푸시 알림 _ 32

by 개발하는윤기사 2023. 7. 27.
728x90
반응형

 

로컬 푸시 알림은 앱 내부에서 생성한 특정 메시지를 전달 유저에게 전달하는 알림입니다!

 

알림이 도착하면 앱 아이콘의 배지에 표시할 수 있어요. 

 

메시지나 카카오톡 보면 메시지가 왔을 때 빨간 배지가 표시되죠? 같은 거라고 보시면 됩니다.

 

로컬 알림의 가장 큰 특징은 정해진 시점(date), 정해진 위치(location), 정해진 시간 간격(time interval)에 맞게 알림을 Custom해 두고, 그 상황에 맞게 알림이 사용자에게 전달된다는 특징이 있습니다!

 

하지만 시점이나 내용을 미리 작성해 둘 수 없는 경우에는 APNs(Apple Push Notification service)와 같은 원격 알림을 이용해야 합니다!

 

원격 알림 또한 다음 글에서 작성할 예정이니 기대해 주세요~

 

글을 시작하기 앞서 로컬 푸시 알림에 대한 Flow에 대해 먼저 보고 가겠습니다!!

 

1. 앱에서 알림 권한 허용 요청 (Alert, Badge, Sound에 대한 허용 요청)

2. 푸시 알림에 전달할 정보를 담음

3. 시간 간격 or 날짜 or 위치에 따른 트리거 설정

4, 푸시 알림 예약 요청

5. 푸시 알림 전송

 

 

1. 알림 권한 요청

- 사용자에게 알림 권한 요청을 해야 알림을 이용할 수 있습니다!

import UserNotifications

//AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
       
       //사용자 Noti 받기
       UNUserNotificationCenter.current().delegate = self
       
       //사용자에게 알림 권한 허용 요청
       UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ success, error in
         if success {
           self.sendNotification(interval: 60)
       	 } else {
       	    print("ERROR")	
         }
      }

       	  return true
      }
}

 

 

 

2. UNMutableNotificationContent

  • 사용자에게 어떤 내용을 보여줄 지에 대한 정보를 담고 있음.
  • title, subtitle, body, sound 등의 정보를 작성할 수 있음

 

3. UNNotificationTrigger

어떤 시점에 발생될 지!

1) 시간 간격(UNTimeIntervalNotificationTrigger)

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: false)

- 특정 시간 간격 이후에 알림 설정이 가능. "타이머"라고 생각하면 편함!

- 최소 60초 이상의 시간 간격일 때만 반복 알림 설정이 가능.

- ex. 86400초 뒤마다 로컬 알람 요청 

2) 캘린더(UNCalendarNotificationTrigger)

var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

- 시간이나 날짜를 정해서 알림 요청을 할 수 있음. Date 객체를 이용해서 지정 가능!

- ex. 매년 12월 25일 알림 요청, 매일 오후 8시 30분 알림 요청

3) 위치 기반(UNLocationNotificationTrigger)

let center = CLLocationCoordinate2D(latitude: 37.335400, longitude: -122.009201)
let region = CLCircularRegion(center: center, radius: 2000.0, identifier: "Headquarters")
region.notifyOnEntry = true
region.notifyOnExit = false
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)

- 특정 위치 정보를 기반으로 알림을 띄울 수 있음. 

- 사용자에게 위치 권한에 대한 허용도 받아야 한다!! 

 

4. UNNotificationRequest

알림 예약 요청

  • 로컬 알림을 예약하기 위해 요청하는 클래스로, 알림을 통해 전달할 정보와 알림 전달을 위한 트리거, 알림에 대한 Identifier를 포함하고 있음. (Identifier, content, trigger를 포함하고 있음)
  • Identifier
    • 알림에 대한 고유한 값으로, 여러 알림을 보내더라도 Identifier가 동일하다면 알림 내용이 수정되는 형태처럼 동작.
    • 여러 알림을 보내더라도 Identifier가 다르다면, 알림이 스택 형태로 쌓이게 됨.
  • content
    • 알림을 통해 전달할 정보를 관장하는 클래스
    • title, subtitle, body, sound 등의 정보를 담고 있음.
  • trigger
    • 등록된 알림이 어떤 시점에 발생할 지에 대한 정보를 담고 있음.
func sendNotification(interval: Double) {

    let notificationContent = UNMutableNotificationContent()

    notificationContent.title = "푸시알림테스트"
    notificationContent.body = "푸시 알림 재미있어요!"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)
    let request = UNNotificationRequest(identifier: "\\(Date())", content: notificationContent, trigger: trigger)

    UNUserNotificationCenter.add(request) { error in
            if let error = error {
                    print("ERROR")
            }
    }
}

 

(추가+) 앱 실행 상태에 따른 처리

- userNotificationCenter(willPresent:_) : 앱이 포그라운드에 있을 때

- userNotificationCenter(didReceive:_) : 앱이 백그라운드 혹은 실행되고 있지 않을 때

//앱이 실행중일 때 로컬 푸시 알림 설정
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    //상단바 알림 처리하기 위함.
    completionHandler([.alert, .sound])
    
}

//앱이 실행중이 아닐 때 로컬 푸시 알림 설정
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    completionHandler([.alert, .badge, .sound])
  
}

 

(추가+) 푸시 알림 확인 후 아이콘 배지 지워주기

//iOS 13.0+ SceneDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
    UIApplication.shared.applicationIconBadgeNumber = 0
}

//iOS 13.0- AppDelegate.swift
func applicationWillEnterForeground(_ application: UIApplication) {
    UIApplication.shared.applicationIconBadgeNumber = 0
}

 

728x90
반응형