
Today 5/15
Notification의 종류에는 local과 server를 통한 push가 있다. 오늘은 이 중 local을 학습한다.
import UserNotifications
let userNotificationCenter = UNUserNotificationCenter.current()선행작업으로 일단 UserNotifications을 import해주고 특이한 점은 여기 속해있는UNUserNotificationCenter을 사용할 때 instance를 직접 생성하는 것이 아닌 current()라는 타입 메서드로 직접 사용한다는 점이다.
알림 권한 요청하기
func requestNotificationAuthorization() {
    let authOptions :UNAuthorizationOptions = [.alert, .badge, .sound]
    userNotificationCenter.requestAuthorization(options: authOptions) { success, error in
        if let error = error {
            print("Error: \(error)")
        }
    }
}알림 request
local Notification의 기본 구조는 content, trigger, request로 이루어져있다. 
content는 알람이 사용자에게 보여주고자하는 모든 정보를 담는다. title, body, badge number, userInfo, attachments 등의 정보가 들어간다.
trigger는 3가지 타입이 올 수 있다. time, calendar, location로 알람이 언제 올지를 결정한다.
request는 content, trigger를 가지고 생성된다. 또한, identifier는 알람을 취소하거나 핸들링할 때 쓰이게 된다.
func sendNotification(seconds: Double) {
    //Notification Contents
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "LocalNoti"
    notificationContent.body = "LocalNotiTest"
    //Notification Trigger
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false)
    //Binding,identifier(handling) -> Request
    let request = UNNotificationRequest(identifier: "testNotification",
                                        content: notificationContent,
                                        trigger: trigger)
    userNotificationCenter.add(request) { error in
        if let error = error {
            print("Notification Error: ", error)
        }
    }
}이미지 추가
//Image Attach
guard let imageURL = Bundle.main.url(forResource: "notiImage", withExtension: ".jpeg") else { return }
let attachment = try! UNNotificationAttachment(identifier: "notiImage", url: imageURL, options: .none)
notificationContent.attachments = [attachment]asset에서 받아오는 것이 아닌 image url을 통해서 받아온다. 서버 연동해서 이미지를 받아올 때의 편의성을 위해 이런 식이 표준인 것 같다.
Foreground에서의 알람처리
여기까지 진행했을 때에는 앱이 foreground에 있을 때(앱이 켜져있고 화면에 있을 때)는 알람이 오지 않는다. 이 상황에서 알람이 오게하기 위해서는 Appdelegate에서 조금의 처리가 필요하다.
userNotificationCenter(_:willPresent:withCompletionHandler:) : 앱이 foreground 상태에서 알림을 수신했을 때 발동되는 메소드import UserNotifications
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    **UNUserNotificationCenter.current().delegate = self**
    return true
}
extension AppDelegate: UNUserNotificationCenterDelegate {
    // 앱이 실행 중 일때 처리하는 메서드
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.list, .banner])
    }
}