Project 27 - Notification

DaY·2021년 6월 21일
1

iOS

목록 보기
51/52
post-thumbnail

UserNotifications

equestAuthorization

알람 권한 요청

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { accepted, error in
    if !accepted {
        print("Notification access denied.")
    }
}

UNMutableNotificationContent

push 알림 메시지 내용 지정

let content = UNMutableNotificationContent()

content.title = "Reminder"
content.body = "Wake up! You have something to do!"
content.sound = UNNotificationSound.default
content.categoryIdentifier = "normal"

UNNotificationRequest

알림 트리거 설정 후 알림 요청

let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
        
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print("Error: " + error.localizedDescription)
    }
}

UNNotificationAttachment

알림 메시지에 이미지를 넣을 경우 사용

if let path = Bundle.main.path(forResource: "clock", ofType: "jpg") {
    let url = URL(fileURLWithPath: path)
            
    do {
        let attachment = try UNNotificationAttachment(identifier: "clock", url: url, options: nil)
        content.attachments = [attachment]
    } catch {
        print("Image not loaded.")
    }
}

Action

date 변경 시 알림 발생

@IBAction func datePickerDidSelectNewDate(_ sender: UIDatePicker) {
    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        delegate.scheduleNotification(at: sender.date)
    }
}

0개의 댓글