[swift] Swift에서 푸시 알림을 사용하여 사진 업로드 알림 제공하기

많은 애플리케이션에서는 사용자에게 사진 업로드가 완료되었음을 알리기 위해 푸시 알림을 사용합니다. Swift에서는 Apple의 UserNotifications 프레임워크를 사용하여 푸시 알림을 구현할 수 있습니다. 이번 튜토리얼에서는 Swift에서 푸시 알림을 사용하여 사진 업로드 알림을 제공하는 방법에 대해 알아보겠습니다.

준비물

  1. 개발 환경: Xcode
  2. Apple 개발자 계정

프로젝트 생성

첫째로, Xcode를 열고 새로운 프로젝트를 생성합니다. 프로젝트 템플릿은 “Single View Application”을 선택하고, 프로젝트 이름을 입력한 후 적절한 위치에 저장합니다.

푸시 알림 권한 요청

일단 프로젝트가 생성되면, AppDelegate.swift 파일을 열고 application(_:didFinishLaunchingWithOptions:) 메서드에서 푸시 알림 권한을 요청하는 코드를 추가합니다.

import UIKit
import UserNotifications

@UIApplicationMain
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
    }

    // ...
}

위 코드는 사용자에게 애플리케이션의 푸시 알림에 대한 권한을 요청합니다. 사용자가 권한을 허용하면 “푸시 알림 권한이 허용되었습니다.” 라는 메시지가 출력되며, 권한을 거부하면 “푸시 알림 권한이 거부되었습니다.” 라는 메시지가 출력됩니다.

푸시 알림 생성

사진 업로드가 완료되었을 때, 푸시 알림을 생성하여 사용자에게 업로드 완료를 알립니다. 이를 위해 푸시 알림과 관련된 기능을 포함하는 별도의 클래스를 만들어보겠습니다. NotificationManager.swift라는 이름으로 새로운 Swift 파일을 생성하고 다음과 같이 코드를 작성합니다.

import Foundation
import UserNotifications

class NotificationManager {
    
    static let shared = NotificationManager()
    private init() {}
    
    func sendPhotoUploadNotification() {
        let content = UNMutableNotificationContent()
        content.title = "사진 업로드 완료"
        content.body = "사진이 성공적으로 업로드되었습니다."
        content.sound = UNNotificationSound.default
        
        let request = UNNotificationRequest(identifier: "photoUploadNotification", content: content, trigger: nil)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("푸시 알림 보내기 실패: \(error.localizedDescription)")
            } else {
                print("푸시 알림이 성공적으로 보내졌습니다.")
            }
        }
    }
}

위 코드에서 sendPhotoUploadNotification() 메서드는 푸시 알림 컨텐츠를 설정하고, UNNotificationRequest를 사용하여 푸시 알림을 보냅니다. identifier 매개변수는 푸시 알림을 식별하는 데 사용되며, 동일한 식별자를 가진 푸시 알림은 중복으로 표시되지 않습니다.

사진 업로드 후 푸시 알림 전송

사용자가 사진을 업로드한 후에는 NotificationManager.shared.sendPhotoUploadNotification() 메서드를 호출하여 푸시 알림을 보냅니다. 적절한 위치에 이 코드를 추가하여 사진 업로드가 완료되었음을 사용자에게 알리면 됩니다.

// 사진 업로드 코드
// ...

// 사진 업로드 완료 후 푸시 알림 전송
NotificationManager.shared.sendPhotoUploadNotification()

푸시 알림 테스트

마지막으로, 애플리케이션을 실행하고 사진을 업로드해보세요. 사진 업로드가 성공하면 푸시 알림이 기기에 표시됩니다.

하지만 푸시 알림은 시스템에 의해 관리되며, 설치된 애플리케이션 또는 기기의 설정에 따라 다양한 동작이 발생할 수 있습니다. 알림을 받지 못하는 경우, 기기의 설정을 확인하고 차단되거나 오류가 발생하지 않았는지 확인해야 합니다.

이제 사진 업로드 알림을 위한 푸시 알림이 준비되었습니다!

결론

이 튜토리얼에서는 Swift에서 푸시 알림을 사용하여 사진 업로드 알림을 제공하는 방법에 대해 알아보았습니다. UserNotifications 프레임워크를 사용하여 푸시 알림 권한을 요청하고, 푸시 알림을 생성하고, 알림을 전송하는 방법을 살펴보았습니다.

더 많은 기능을 사용하고자 하는 경우, Apple의 공식 문서인 UserNotifications Framework Documentation를 참조해보세요.