1. 사용자에게 푸시 알림 권한 요청하기
import UIKit
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("푸시 알림 권한이 허용되었습니다.")
} else {
print("푸시 알림 권한이 거부되었습니다.")
}
}
return true
}
// ...
}
앱이 시작될 때 application(_:didFinishLaunchingWithOptions:)
메서드에서 UNUserNotificationCenter.current().requestAuthorization()
을 호출하여 사용자에게 푸시 알림 권한을 요청합니다. 사용자가 권한을 허용하면 granted
에 true
가 전달되고, 권한이 거부되면 granted
에 false
가 전달됩니다.
2. 푸시 알림 등록하기
import UIKit
import UserNotifications
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().delegate = self
}
// ...
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
// ...
}
푸시 알림을 사용하기 위해서는 UNUserNotificationCenter
및 UIApplicationDelegate
의 메서드를 사용해야 합니다. 위 코드에서 registerForPushNotifications()
메서드를 호출하여 권한을 확인하고, getNotificationSettings()
메서드에서 설정을 가져온 후, registerForRemoteNotifications()
메서드를 호출하여 푸시 알림을 등록합니다.
3. 푸시 알림 수신 및 처리하기
import UIKit
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// ...
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if let aps = userInfo["aps"] as? [String: Any] {
processNotification(aps)
}
}
func processNotification(_ aps: [String: Any]) {
if let alert = aps["alert"] as? String {
let alertController = UIAlertController(title: "푸시 알림", message: alert, preferredStyle: .alert)
let okAction = UIAlertAction(title: "확인", style: .default, handler: nil)
alertController.addAction(okAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
}
// ...
}
앱이 실행되고 있을 때, 푸시 알림을 수신하면 application(_:didReceiveRemoteNotification:)
메서드가 호출됩니다. 이 메서드 안에서는 전달된 알림에 대한 처리를 할 수 있습니다. 위 코드에서는 aps
딕셔너리에서 알림 메시지를 추출하여 경고창으로 보여주도록 구현하였습니다.
마무리
위의 예시 코드를 사용하여 Swift로 푸시 알림을 통한 사용자 인터랙션을 구현하는 방법에 대해 알아보았습니다. 앱에 푸시 알림을 사용하고자 한다면, 이 방법을 활용해보세요. 사용자에게 중요한 정보를 전달하고, 앱에 대한 인터랙션을 유도할 수 있을 것입니다.
더 자세한 내용은 Apple Developer Documentation을 참조해주세요.