JJ_iOS/JJUNGTABLE/APP/AppDelegate.swift
2024-06-26 12:38:42 +09:00

377 lines
16 KiB
Swift

//
// AppDelegate.swift
// JJUNGTABLE
//
// Created by Sean Kim on 10/26/23.
//
import UIKit
import SwiftUI
import Combine
import UserNotifications
import Firebase
import FirebaseMessaging
import KakaoSDKCommon
@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate{
var viewModel = ViewModel()
private var cancellables = Set<AnyCancellable>()
private var version: [Version] = []
private let gcmMessageIDKey = "gcm.message_id"
// private var cancellables = Set<AnyCancellable>()
// private var versions: [Version] = []
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
}
private func checkVersion() {
API.shared.readData(path: "/db/version/read",
queryItems: [URLQueryItem(name: "os_type", value: "I")])
.sink { completion in
switch completion {
case .finished:
printLog(self.version)
// OOO
switch compareVersion(currentVersion(), self.version[0].update_ver) {
case .bigger:
self.viewModel.isUpdate = "N"
case .smaller, .equal:
self.viewModel.isUpdate = "Y"
case .error:
self.viewModel.alertData = self.viewModel.systemErrorAlert()
self.viewModel.showAlert.toggle()
}
switch compareVersion(currentVersion(), self.version[0].final_ver) {
case .bigger, .equal:
// - x
break
case .smaller:
let choice = self.version[0].update_choice == "Y" ? true : false
switch compareVersion(currentVersion(), self.version[0].force_ver) {
case .bigger, .equal:
//
if !choice {
break //
}
else {
self.viewModel.alertData = .init(title: "업데이트 안내",
body: """
앱 최신 버전이 새로 나왔습니다.
지금 업데이트 하시겠어요?
""",
button: [ButtonType(name: "지금 업데이트", role: .cancel ,
function: {exit(1)}),
ButtonType(name: "나중에", role: .none ,
function: nil),
])
self.viewModel.showAlert.toggle()
}
case .smaller:
// -> .
self.viewModel.alertData = .init(title: "업데이트 안내",
body: """
시스템이 제대로 동작하지 못했습니다.
앱을 종료후 다시 실행해주세요.
""",
button: [ButtonType(name: "지금 업데이트", role: .none,
function: {exit(1)})])
self.viewModel.showAlert.toggle()
case .error:
self.viewModel.alertData = self.viewModel.systemErrorAlert()
self.viewModel.showAlert.toggle()
}
case .error:
self.viewModel.alertData = self.viewModel.systemErrorAlert()
self.viewModel.showAlert.toggle()
}
//
case .failure(let error):
printLog(error)
self.viewModel.alertData = self.viewModel.systemErrorAlert()
self.viewModel.showAlert.toggle()
}
} receiveValue: { data in
do {
let decoder = JSONDecoder()
self.version = try decoder.decode([Version].self, from: data)
} catch {
printLog(error)
self.viewModel.alertData = self.viewModel.systemErrorAlert()
self.viewModel.showAlert.toggle()
}
}
.store(in: &cancellables)
}
}
// MARK: -
extension AppDelegate {
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
printLog("Start Set AppDelegate")
if isIllegalDevice() {
viewModel.alertData = .init(title:"경고",
body: """
변경된 OS('탈옥'등)의 스마트폰은 서비스를 이용할수 없습니다.
""",
button: [ButtonType(name: "확인", role: .none ,
function: {exit(1)})])
viewModel.showAlert.toggle()
}
else {
checkVersion()
// Firebase
FirebaseApp.configure()
// App Check
// AppCheck.setAppCheckProviderFactory(AppCheckDebugProviderFactory())
// SDK
KakaoSDK.initSDK(appKey: KEY.kakaoAppKey)
#if FCM
// FCM
Messaging.messaging().delegate = self
#endif
// Noti
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in
if let error = error {
printLog("Authorization error: \(error.localizedDescription)")
}
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
printLog("Notification permission denied.")
}
}
application.registerForRemoteNotifications()
UIApplication.shared.registerForRemoteNotifications()
//
_ = NetworkMonitor.shared
}
printLog("End Set AppDelegate")
return true
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
}
extension AppDelegate {
// 24.05.30 () -
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// SMS
Auth.auth().setAPNSToken(deviceToken, type: .unknown)
printLog("원격 푸시 알림 등록 성공 ")
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02.2hX", $1)})
viewModel.deviceToken = deviceTokenString
// Firebase
Messaging.messaging().apnsToken = deviceToken
printLog("DeviceToken: \(viewModel.deviceToken)")
}
// 24.05.30 () - FCM
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
@UserDefault (key: "isRegisterToken", defaultValue: "F") var isRegisterToken
printLog("토큰 등록 동작 시작")
guard let fcmToken = fcmToken else { return }
viewModel.pushFCMToken = fcmToken
Task {
if isRegisterToken == "F" {
// switch await FB_CRUD.shared.create("Token", doc: "\(viewModel.deviceToken)",
// data: ["fcmToken":"\(viewModel.pushFCMToken)"]) {
// case .success(_):
// viewModel.pushFCMToken = fcmToken
// isRegisterToken = "T"
// printLog(" ")
// case .failure(let error):
// isRegisterToken = "F"
// viewModel.alertData = .init(body:"""
// .
// .
// """,
// button: [ButtonType(name: "", role: .destructive ,function: {exit(1)})])
// viewModel.showAlert.toggle()
// printLog(" ")
// }
}
else {
// if viewModel.pushFCMToken != fcmToken {
// switch await FB_CRUD.shared.update("Token", doc: "\(viewModel.deviceToken)",
// data: ["fcmToken":"\(viewModel.pushFCMToken)"]) {
// case .success(_):
// viewModel.pushFCMToken = fcmToken
// isRegisterToken = "T"
// printLog(" ")
// case .failure(_):
// viewModel.alertData = .init(body:"""
// .
// .
// """,
// button: [ButtonType(name: "", role: .destructive ,function: {exit(1)})])
// viewModel.showAlert.toggle()
// printLog(" ")
// }
// }
}
printLog("FCM Token: \(viewModel.pushFCMToken)")
}
}
//
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
let userInfo = notification.request.content.userInfo
// SMS
if Auth.auth().canHandleNotification(userInfo) {
return []
}
if let apsData = userInfo["aps"] as? [AnyHashable: Any],
let messageId = userInfo["gcm.message_id"] as? String,
let badge = apsData["badge"] as? Int {
// switch await FB_CRUD.shared.read("Users", doc: "\(viewModel.userId)") {
// case .success(let data):
// if var noReadList = data["noReadAlert"] as? [String] {
// noReadList.append(messageId)
// viewModel.noReadAlertList = noReadList
// switch await FB_CRUD.shared.update("Users", doc: "\(viewModel.userId)",
// data: ["noReadAlert":noReadList]) {
// case .success(let data):
// await viewModel.setBadge()
// case .failure(let gg):
// printLog(noReadList)
// }
// printLog(viewModel.noReadAlertList)
// printLog(viewModel.noReadAlertList.count)
//
// }
// case .failure(let failure):
// printLog(failure)
// }
}
Messaging.messaging().appDidReceiveMessage(userInfo)
if #available(iOS 14.0, *) {
return [[.list,.banner,.sound]]
} else {
return[[.alert,.sound]]
}
}
// Background Notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) {
printLog("ININININININi")
let userInfo = response.notification.request.content.userInfo
// SMS
if Auth.auth().canHandleNotification(userInfo) {
return
}
if let apsData = userInfo["aps"] as? [AnyHashable: Any] {
if let alert = apsData["alert"] as? [AnyHashable: Any],
let messageKey = apsData[gcmMessageIDKey] as? String {
printLog("apsData: \(apsData)")
printLog("alert: \(alert)")
printLog("key: \(messageKey)")
if let param = alert["parameter"] {
printLog(param as? String)
}
// viewModel.setBadge()
}
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// SMS
if Auth.auth().canHandleNotification(userInfo) {
completionHandler(.noData)
return
}
// printLog("Back = \(userInfo)")
// FB_CRUD.shared.sendPushNotification("", body: "")
// @UserDefault (key: "fcmToken", defaultValue: "") var pushFCMToken
// @UserDefault (key: "userId", defaultValue: "") var userId
// @UserDefault (key: "noReadAlertList", defaultValue: [""]) var noReadAlertList
//
// let userInfo = notification.request.content.userInfo
//
// if let apsData = userInfo["aps"] as? [AnyHashable: Any],
// let messageId = userInfo["gcm.message_id"] as? String,
// let badge = apsData["badge"] as? Int {
//
// switch await FB_CRUD.shared.read("Users", doc: "\(userId)") {
// case .success(let data):
// printLog(data)
// if var noReadList = data["noReadAlert"] as? [String] {
// noReadList.append(messageId)
// noReadAlertList = noReadList
// await FB_CRUD.shared.update("Users", doc: "\(userId)",
// data: ["noReadAlert":noReadList])
// printLog(noReadList)
// printLog(noReadAlertList)
// printLog(noReadAlertList.count)
// await viewModel.setBadge(badge: noReadAlertList.count)
// }
// case .failure(let failure):
// printLog(failure)
// }
//
// }
}
}