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])
}
}