1. PUSH 설정 Project -> TARGETS -> Signing & Capabilities
(1) + Capability 클릭
1) Background Modes 추가
- Background fetch 체크
- Remote norifications 체크
2) Push Notifications 추가
2. PUSH 권한 요청 및 Device Token 값 처리
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...... 생략 .......
// NotificationCenter 등록
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization( //알림,배지,사운드에 대한 권한 요청
options: authOptions,
completionHandler: { (granted, error) in
if granted {
log(direction: .ETC, ofType: self, datas: "사용자가 푸시를 허용했습니다.")
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else {
log(direction: .ETC, ofType: self, datas: "사용자가 푸시를 거절했습니다.")
}
})
application.applicationIconBadgeNumber = 0
...... 생략 .......
}
// MARK: APNS 디바이스 토큰
// deviceToken 등록 성공시 실행되는 메서드
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
/*
** 시뮬레이터는 디바이스토큰 사용불가. 물리디바이스 확인 필요
*/
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
log(direction: .RECEIVE, ofType: self, datas: "Device Token - \(deviceTokenString)")
// 토큰값 처리
}
// deviceToken 등록 실패시 실행되는 메서드
internal func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
log(direction: .RECEIVE, ofType: self, datas: "Device Token 등록 실패 - \(error.localizedDescription)")
}
}
3. UNUserNotificationCenterDelegate 추가
- 실행 상태에서 백그라운드와 포그라운드 상태에 따라 노티 클릭시 들어오는 함수가 다름을 주의 하자
// MARK: UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
//실행되고 있는 상태에서 PUSH 클릭시 (백그라운드 -> 포그라운드)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
log(direction: .OBSERVER, ofType: self, datas: "\(userInfo)")
completionHandler()
}
//PUSH 포그라운드 상태에서 푸쉬 들어올 경우 호출
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
log(direction: .OBSERVER, ofType: self, datas: "\(userInfo)")
// completionHandler([]) //포그라운드 상태에서 알림 안받으려면
// 베너 알림창 노출 시키고 클릭시 didReceive 호출됨.
if #available(iOS 14.0, *) {
//.list 알림센터에만 표시됨
//.banner 상단에 배너 형태로 표시됨
completionHandler([.banner, .list, .badge, .sound])
} else {
completionHandler([.alert, .badge, .sound])
}
}
}
'Swift > Push Notification' 카테고리의 다른 글
[SWIFT]이미지 푸쉬 메세지 NotificationService (0) | 2023.06.27 |
---|---|
[SWIFT]#2. 앱 종료상태에서 알림 클릭시 커스텀 데이터 처리 (0) | 2023.04.14 |