[swift] Swift에서 푸시 알림을 사용하여 체크인 알림 제공하기

푸시 알림은 앱 사용자에게 중요한 소식을 전달하고 다양한 기능을 제공하는 강력한 도구입니다. Swift 언어를 사용하여 푸시 알림 기능을 구현하려는 경우, 앱 유저가 체크인할 때 알림을 보내는 기능을 추가할 수 있습니다. 이를 통해 유저에게 소셜 기능을 제공하고 앱 사용 경험을 향상시킬 수 있습니다.

사용자에게 허용을 요청하기

푸시 알림을 사용하기 위해서는 앱이 유저에게 알림을 보낼 수 있는 권한을 요청해야 합니다. 이를 위해 아래와 같이 AppDelegate.swift 파일에서 application(_:didFinishLaunchingWithOptions:) 함수를 수정합니다:

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, .sound, .badge]) { (granted, error) in
            if granted {
                print("푸시 알림 권한이 허용되었습니다.")
            } else {
                print("푸시 알림 권한이 거부되었습니다.")
            }
        }
        
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
    
    // 푸시 알림 설정을 위한 함수
    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            print("푸시 알림 권한: \(granted)")
        }
    }
    
    // 푸시 알림 등록에 성공한 후에 호출되는 함수
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("디바이스 토큰: \(deviceTokenString)")
    }

    // 푸시 알림 등록에 실패한 후에 호출되는 함수
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("푸시 알림 등록 실패: \(error.localizedDescription)")
    }
    
    // 앱이 foreground에서 실행 중일 때 알림이 도착했을 때 호출되는 함수
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .sound, .alert])
    }

    // 푸시 알림이 사용자에게 표시된 후 호출되는 함수
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
}

위 코드에서 application(_:didFinishLaunchingWithOptions:) 함수는 앱이 시작될 때 호출되며, 푸시 알림 권한을 요청하고 설정을 초기화합니다. registerForPushNotifications() 함수는 따로 푸시 알림 권한을 요청하기 위한 함수로 사용할 수 있습니다.

푸시 알림 보내기

이제 앱에서 체크인한 유저에게 푸시 알림을 보내는 기능을 추가해보겠습니다. 푸시 알림은 서버에서 직접 보내거나, 앱 내에서 클라이언트 측에서 보낼 수 있습니다. 이 예시에서는 클라이언트 측에서 푸시 알림을 보내는 방법을 보여드리겠습니다.

import UIKit
import UserNotifications

func sendCheckInNotification() {
    let content = UNMutableNotificationContent()
    content.title = "체크인 알림"
    content.body = "오늘도 고생하셨어요!"
    content.sound = UNNotificationSound.default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "checkInNotification", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            print("푸시 알림 전송 실패: \(error.localizedDescription)")
        } else {
            print("푸시 알림 전송 성공!")
        }
    }
}

// 체크인한 유저에게 알림 보내기
sendCheckInNotification()

위의 코드에서 sendCheckInNotification() 함수는 체크인한 유저에게 알림을 보내는 역할을 합니다. UNMutableNotificationContent()를 사용하여 알림의 내용을 설정하고, UNTimeIntervalNotificationTrigger를 사용하여 특정 시간 이후에 알림이 보이도록 설정합니다. UNNotificationRequest를 사용하여 알림을 요청하고, UNUserNotificationCenter.current().add(request) 함수를 통해 알림을 전송합니다.

이렇게 Swift에서 푸시 알림을 사용하여 체크인 알림을 제공할 수 있습니다. 추가적인 설정이나 기능을 구현하려면 Apple의 UNUserNotificationCenter 문서를 참고하시기 바랍니다.