천원의 개발

iOS Local Notification 사용법 본문

iOS&Swift🍎/iOS

iOS Local Notification 사용법

천 원 2022. 7. 29. 14:49

Notification: 사용자 디바이스에 앱의 알림을 표시하는 기능이 담긴 프레임워크!

 

1. 인스턴스 생성!

let notificationCenter = UNUserNotificationCenter.current()

2. 권한 요청 생성!

func requestAuthorization(){

	// UNAuthorizationOptions 인스턴스 생성해서 options에 넣어 줍니다
    let authorizationOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
	
    // 권한 요청 (alert, badge, sound에 대한 권한 요청)
    notificationCenter.requestAuthorization(options: authorizationOptions) { success, error in
        if success {
            self.sendNotification()
        } else {
            print("error!!")
        }
    }
}

3. Content 인스턴스 생성하여 알림 제목, 내용등을 설정

func sendNotification(){
    let notificationContent = UNMutableNotificationContent()

    notificationContent.title = "오늘은 어떤 빵을 먹을까요?"
    notificationContent.body = "따끈따끈 소보루"
    notificationContent.badge = 1

4. Trigger를 통해서 언제 알림을 보낼지 설정

func sendNotification(){
    	...
    
    // 시간 간격으로 설정 -> 60초뒤에 실행!
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)

	// 날짜 간격으로 설정 -> 매시간 15분에 한번씩 실행!
    var dateComponents = DateComponents()
    dateComponents.minute = 15
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)


    }

5. request를 통해 설정한 Content와 Trigger를 등록 해준다!

  func sendNotification(){
  		...
                
      let request = UNNotificationRequest(identifier: "\(Date())", content: notificationContent, trigger: trigger)

        notificationCenter.add(request)
	}

여기서 identifier를 동일하게 설정하면 같은 알람으로 취급하여 이전의 알람은 사라지게 되고 다르게 설정해주면 스택처럼 쌓이게 된다

따란~~

6. identifier로 제거

notificationCenter.removePendingNotificationRequests(withIdentifiers: [identifier])

 

7. 특정 날짜로 notification 등록

let notificationContent = UNMutableNotificationContent()
notificationContent.title = "test"
notificationContent.body = "test"
notificationContent.badge = 1 // badge

let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: Date().addingTimeInterval(86400 * 100))
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest("Test", content: notificationContent, trigger: trigger)
notificationCenter.add(request)

 

8. 포그라운드에서도 알림 받을 수 있게

 

 

AppDelegate :  UNUserNotificationCenterDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    //2. 노티 제거
    UNUserNotificationCenter.current().removeAllDeliveredNotifications() // 사용자에게 이미 도착한 노티만 제거
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests() // 사용자가 받을 예정인 노티도 제거
    UNUserNotificationCenter.current().delegate = self // Delegate

    return true
}

// 포그라운드시에도 알림 받을 수 있게
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([ .list, .banner, .badge, .sound]) // iOS 14 list, banner <-> alert

}

Badge제거

 UIApplication.shared.applicationIconBadgeNumber = 0

 

'iOS&Swift🍎 > iOS' 카테고리의 다른 글

iOS HTTP 통신 허용  (0) 2022.08.13
iOS 커스텀 폰트 사용법  (0) 2022.08.11
iOS UserDefaults 사용법  (0) 2022.07.17
iOS Alert 사용법  (0) 2022.07.15
iOS DateFormatter 사용법  (0) 2022.07.14