[swift] Swift에서 푸시 알림을 사용하여 웨더 앱 개발하기

지금은 모바일 앱 개발에서 푸시 알림이 매우 중요한 기능이 되었습니다. 앱 사용자에게 실시간으로 중요한 정보를 전달하고, 앱을 사용하지 않을 때에도 사용자의 관심을 유지할 수 있기 때문입니다.

이번 블로그 포스트에서는 Swift 프로그래밍 언어를 사용하여 푸시 알림을 구현하는 방법을 소개하겠습니다. 특히, 날씨 앱을 예로 들어 실제로 푸시 알림을 사용하는 방법을 알아보겠습니다.

1. 프로젝트 설정

먼저, Xcode에서 새로운 프로젝트를 생성합니다. Single View Application 템플릿을 선택하고, 프로젝트 이름을 “WeatherApp”으로 설정합니다.

2. 라이브러리 추가

푸시 알림을 구현하기 위해 필요한 라이브러리들을 추가합니다. 프로젝트의 Podfile에 아래와 같이 추가합니다:

target 'WeatherApp' do
  use_frameworks!
  pod 'Firebase/Messaging'
end

그런 다음 터미널에서 pod install 명령어를 실행하여 라이브러리를 설치합니다.

3. Firebase 설정

  1. Firebase Console(https://console.firebase.google.com/)에 접속하고, 새 프로젝트를 생성합니다.
  2. Firebase 프로젝트 설정 페이지에서 “iOS 앱 추가”를 클릭합니다. 앱의 번들 식별자와 앱 이름을 입력합니다.
  3. GoogleService-Info.plist 파일을 다운로드하여 프로젝트에 추가합니다.

4. APNs 인증서 생성

  1. Apple 개발자 계정에서 인증서 생성 페이지로 이동합니다.
  2. 인증서 요청서를 작성하고, Apple Push Notification 서비스 SSL (Sandbox & Production)를 선택합니다.
  3. 인증서를 생성하고, Certificates.p12 파일을 다운로드합니다.

5. 프로젝트 설정

  1. Xcode에서 프로젝트를 열고, AppDelegate.swift 파일을 엽니다.
  2. 아래의 코드를 didFinishLaunchingWithOptions 메서드에 추가합니다:
import Firebase

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  FirebaseApp.configure()

  return true
}
  1. AppDelegate.swift 파일에서 아래의 코드를 추가하여 APNs 설정을 수행합니다:
import UserNotifications

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Messaging.messaging().apnsToken = deviceToken
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print("Failed to register for remote notifications: \(error.localizedDescription)")
}
  1. 앱에 푸시 알림을 활성화하려면 Info.plist 파일에 아래의 키를 추가합니다:
<key>UIBackgroundModes</key>
<array>
  <string>remote-notification</string>
</array>

6. 푸시 알림 처리

  1. ViewController.swift 파일을 열고, 푸시 알림을 처리할 Notification Extension을 생성합니다:
import UserNotifications

class NotificationService: UNNotificationServiceExtension {
  override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    guard let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
      return
    }
    // 푸시 알림 내용 변경
    bestAttemptContent.title = "새로운 날씨 정보가 도착했습니다!"
    
    contentHandler(bestAttemptContent)
  }
}
  1. AppDelegate.swift 파일에 추가합니다:
import UserNotifications

class AppDelegate: NSObject, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
  // Firebase push notification 설정...
  
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(.alert)
  }
  
  // ...
}

7. 푸시 알림 테스트

푸시 알림을 테스트하려면, Firebase Console에서 테스트 알림을 보낼 수 있습니다. Console에서 앱에 푸시 알림을 보내면 앱이 백그라운드에 있을 때 알림이 표시됩니다.

이제 위의 단계를 따라하면서 Swift에서 푸시 알림을 사용하여 Weather 앱을 개발할 수 있습니다. Firebase와 APNs를 통합하여 안정적으로 푸시 알림을 전송할 수 있습니다. 다양한 앱에서 푸시 알림을 사용하여 사용자 경험을 향상시키세요!

참고 자료