Notice
Recent Posts
Recent Comments
Link
Ssul's Blog
ios push알림 기능 설정 본문
1. IOS Push알림 개념이해
ios는 서버에서 직접 푸쉬를 보낼수 없다. 중간에 APNs가 존재해서, 서버에서 push를 보내려면, APNs에게 보내고, 그걸 클라이언트에 보내는 구조이다.
아래 그림과 같은 구조이다
(1-2) 개인 핸드폰이 APNs에게 연결을 요청하고, 자신 고유의 토큰을 받는다.
(3) 자신의 APNs고유 토큰을 서버에게 알려준다
(4) 서버에서 push를 보내려면 APNs에게 클라이언트 토큰과 내용(payload), APN key를 보낸다
(5) APNs는 검증을 마치고 push알림을 보낸다
2. 설정하기
2-1. xCode에서 push Notifications 추가하기
xCode - TARGETS - 프로젝트명 - Signing&Capabilities탭 - +Capability - push notifications추가
(*애플 개발자계정(유료)이어야 하고, 위에 signing에 automatically manage signing체크 확인)
2-2. firebase messaging라이브러리 추가(서버로 해도 됨)
xCode - TARGETS - 프로젝트명 - General탭 - frameworks.... - firebaseMessaging 추가
2-3. developer사이트에서 추가해주기
- developer.apple.com 들어가서 > key로 가서 > 추가
- 키파일은 한번다운 받으면 다시 못받으니, 잘 저장해두기
2-4. firebase console셋팅
로그인 > 프로젝트 > 프로젝트 설정 > 클라우드 메세징탭 > APN인증 키 업로드 + 키id, 팀id입력
3. 설정하기
3-1. AppDelegate수정
import SwiftUI
import FirebaseCore
import FirebaseAuth
import GoogleSignIn
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// APNs에 해당 앱 등록요청
application.registerForRemoteNotifications()
// 알림작업 하는 친구 연결
UNUserNotificationCenter.current().delegate = self
FirebaseApp.configure()
return true
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance.handle(url)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// forground상에서 push 메세지 받았을때
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .banner])
}
// 알림메세지를 눌렀을때 처리하는 작업
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
}
3-2. 알림 권한 얻기
- 보통 로그인 완료시 호출
//ViweModel에 추가해야하고,
case .requestPushNotification:
container.services.pushNotificationService.requestAuthorization { [weak self] granted in
guard granted else { return }
self?.send(action: .setPushToken)
}
case .setPushToken:
container.services.pushNotificationService.fcmToken
.compactMap { $0 }
.flatMap { [weak self] fcmToken -> AnyPublisher<Void, Never> in
guard let `self` = self, let userId = self.userId else { return Empty().eraseToAnyPublisher() }
return self.container.services.userService.updateFCMToken(userId: userId, fcmToken: fcmToken)
.replaceError(with: ())
.eraseToAnyPublisher()
}
.sink { _ in
}.store(in: &subscriptions)
//View에 추가해야 함
// 인증 완료 -> MainTabView 표시
MainTabView(container: container)
.environmentObject(authViewModel)
.onAppear {
authViewModel.send(action: .requestPushNotification)
}
이후에는 자신의 서비스에 따라, 구조를 잡아서 코딩을 진행하여야 함
'dev > 기능구현' 카테고리의 다른 글
IOS 앱개발 String Catalog로 한국어, 영어 (다국어)동시설정(swiftui) (0) | 2025.04.02 |
---|---|
[ChatGPT, DALLE2] 인공지능 카카오챗봇 만들기 (2) | 2024.02.07 |
[Django, tailwind] AI가 상담글에 자동으로 댓글 달아주기 #2 (react, tailwind) (1) | 2024.01.24 |
[Django, tailwind] AI가 상담글에 자동으로 댓글 달아주기 #1(signal, threading사용) (0) | 2024.01.18 |
Youtube 영상 정보/자막 정보 추출방법 (2) | 2024.01.12 |