IOS

IOS - 사용자에게 알람 승인을 구하는 법.

clamp 2022. 4. 24. 13:30

우리들은 앱을 처음 설치하고 열었을 때 "이 앱에서 오는 알림을 받으시겠습니까?" 하는 별도에 Alert을 기억 할텐데 그런 식으로 만약에 사용자가 허용을 하지 않으면 우리가 잘 설정해 놓은 이런 알람도 사실상 앱에 표현되지 않는다.

어쨋든 이러한 허용을 받아야만 보낼 수 있는 구조로 되어있기 때문에, 사용자의 승인을 구하는 코드를 추가해야한다.

 

AppDelegate.swift파일에서 UserNotifications를 추가해준다.

//AppDelegate.swift
import UIKit
import UserNotifications

 

그리고 didFinishLaunchingWithOption에서 구현한다.

class AppDelegate: UIResponder, UIApplicationDelegate {
	
    //UNUserNotificationCenter객체를 생성.
    var userNotificationCenter: UNUserNotificationCenter?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        UNUserNotificationCenter.current().delegate = self
        
        //notification Option들을 생성 하는데 arrayLiteral로 해서, alert, badge, sound에 대한 허락을 구한다.
        let authrizationOptions = UNAuthorizationOptions(arrayLiteral: [.alert, .badge, .sound])
        
        //userNotificationCenter는 인증을 request(요청)할 수 있다. 옵션은 위에 생성해놓은 옵션이고, 
        //completionHandler를 통해서 에러처리를 할 수 있다. 결과값은 무시하고 에러 처리정도만 해줌.
        userNotificationCenter?.requestAuthorization(options: authrizationOptions){ _, error in
            if let error = error{
                print("ERROR: notification authrization request \(error.localizedDescription)")
            }
        }
        return true
    }