[swift] 앱에서의 알림 수신 및 처리 과정

알림은 모바일 앱 개발에서 중요한 요소입니다. 사용자에게 중요한 정보를 전달하고, 상호작용을 유발하여 앱 이용을 촉진시킬 수 있습니다. 이번 블로그 포스트에서는 Swift를 사용하여 iOS 앱에서 알림을 수신하고 처리하는 과정에 대해 알아보겠습니다.

알림의 기본 동작

iOS에서의 알림은 “로컬 알림”과 “원격 알림”(APNs)으로 구분됩니다.

로컬 알림은 앱 내에서 생성하고 명시적으로 예약한 알림이며, 사용자의 장치에 직접 전송됩니다.

원격 알림은 앱 서버에서 생성되며, APNs를 통해 앱에 전달됩니다. 사용자의 장치에 도달하기 전에 APNs 서버를 거치게 되는데, 이를 통해 알림을 수신하고 처리할 수 있습니다.

알림 처리를 위한 설정

알림을 처리하기 위해 앱에는 알림 권한을 요청하는 코드를 추가해야 합니다. AppDelegate 파일에서 다음과 같은 코드를 작성합니다.

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 알림 권한 요청
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("알림 권한이 승인되었습니다.")
            } else {
                print("알림 권한이 거부되었습니다.")
            }
        }
        
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
    
    // 앱이 foreground에서 동작 중일 때 알림 수신 처리
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 앱이 실행 중일 때 알림 수신 처리 로직 작성
        // completionHandler()를 호출하여 알림을 표시할 방식을 지정합니다.
        completionHandler([.alert, .badge, .sound])
    }
    
    // 알림을 터치하여 앱 실행 시 알림 처리
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 알림 터치 시 앱을 실행하고 알림 처리 로직 작성
        completionHandler()
    }
    
}

위의 코드에서 주목해야 할 부분은 다음과 같습니다.

  1. AppDelegate 클래스가 UNUserNotificationCenterDelegate 프로토콜을 채택하고 있다는 점입니다.
  2. application(_:didFinishLaunchingWithOptions:) 메서드에서 알림 권한을 요청하고, 권한이 승인되면 알림 권한을 사용할 수 있다는 메시지를 출력합니다.
  3. userNotificationCenter(_:willPresent:withCompletionHandler:) 메서드는 앱이 foreground에서 동작 중이고 알림을 수신할 때 호출됩니다. 여기에 알림 수신 시 처리할 로직을 작성하고 알림을 표시할 방식을 completionHandler에 전달합니다.
  4. userNotificationCenter(_:didReceive:withCompletionHandler:) 메서드는 알림을 터치하여 앱을 실행할 때 호출됩니다. 여기에 알림 터치 시 처리할 로직을 작성하고 completionHandler를 호출합니다.

알림 발송

알림을 수신하려면 먼저 앱 서버에서 알림을 발송해야 합니다. 원격 알림을 발송하기 위해서는 APNs 서비스를 사용해야 하며, 이에 대해 자세한 내용은 Apple Developer 사이트를 참고하시기 바랍니다.

로컬 알림은 앱 내에서 직접 생성하고 예약할 수 있습니다. 다음은 로컬 알림을 생성하고 예약하는 예제입니다.

import UIKit
import UserNotifications

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 로컬 알림 생성
        let content = UNMutableNotificationContent()
        content.title = "알림 제목"
        content.body = "알림 내용"
        
        // 예약 시각 설정
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
        
        // 로컬 알림 요청 생성
        let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
        
        // 로컬 알림 예약
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("로컬 알림 예약 실패: \(error)")
            } else {
                print("로컬 알림 예약 성공")
            }
        }
    }

}

위의 코드에서는 ViewController의 viewDidLoad() 메서드에서 로컬 알림을 생성하고 예약하는 과정을 보여줍니다. UNMutableNotificationContent 객체를 생성하여 알림의 제목과 내용을 설정하고, UNTimeIntervalNotificationTrigger 객체를 생성하여 알림의 예약 시각을 설정합니다. 마지막으로 UNNotificationRequest 객체를 생성하여 로컬 알림을 요청하고 UNUserNotificationCenter.current().add(request)를 호출하여 알림을 예약합니다.

참고 자료

  1. Apple Developer Documentation - User Notifications
  2. Apple Developer Documentation - Local and Remote Notification Programming Guide