티스토리 뷰

IOS/ios

ios - 로컬 푸시 알림

내일도이렇게 2021. 12. 12. 15:59

로컬에서 푸쉬 알림을 구현하는 방법을 알아보고자 한다. 

import UserNotifications
let userNotificationCenter = UNUserNotificationCenter.current()

override func viewDidLoad() {
    super.viewDidLoad()
    
    requestNotificationAuthorization()

}

requestNotificationAuthoriztion 으로 알람 권한 요청 

 func requestNotificationAuthorization() {
        
        let authOpthions = UNAuthorizationOptions(arrayLiteral: .alert,.badge,.sound)
        
            userNotificationCenter.requestAuthorization(options: authOpthions) {
                success, error in
                      if success {
                          // 성공 로직 
				}
         } 
   }

 

Local Notification 은  content, trigger, request 를 통해 구현 

 

content : 사용자에게 어떤 내용을 보여줄지에 대한 정보를 담는다. 

 

trigger :  time, calendar , location 타입으로 지정

            - time : 일정 시간이 지난 후에 작동 

            - calendar : 특정한 날짜에 작동 

            - location : 특정 위치에 진입할 경우  
        

request :  content 와 trigger 로 로컬 푸쉬를 등록,identifier 로 식별자 지정해야 해당 알림을 취소하거나 핸들링할 때 사용

    func sendNotification(scheduleUUID : String , alarmTitle : String, alarmDate : Date){
        
        let notificationContent = UNMutableNotificationContent()

        notificationContent.title = alarmTitle
        notificationContent.badge = 1

        
        let dateComponets = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: alarmDate)
            
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponets, repeats: false)
            
        let request = UNNotificationRequest(identifier: scheduleUUID ,
                                                 content: notificationContent,
                                                 trigger: trigger)
        
        userNotificationCenter.add(request) { error in
            if let error = error {
                            print("Notification Error: ", error)
                        }
            }
    }

-->  특정시간에 알림 

notification  앱이 실행중인 상태에서도 알림을 받기위해  AppDelegate 에서 처리 필요 

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
     UNUserNotificationCenter.current().delegate = self
     
     return true 
} 


extension AppDelegate : UNUserNotificationCenterDelegate {
    
    // 3. 앱이 foreground상태 일 때, 알림이 온 경우 어떻게 표현할 것인지 처리
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        // 푸시가 오면 alert, badge, sound표시를 하라는 의미
        completionHandler([.alert, .badge, .sound])
    }
    
 }

 

'IOS > ios' 카테고리의 다른 글

iOS 환경별 Build 세팅  (0) 2023.04.09
Application 상태값  (0) 2023.04.09
Carthage 설치 및 사용  (0) 2022.03.14
매매노트앱 회고록  (0) 2021.12.10
매매노트 - 개인정보 처리방침  (0) 2021.12.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함