增加push功能。

This commit is contained in:
oscarz
2024-09-10 16:39:30 +08:00
parent 5b3b2f4a5f
commit 434df13a41
6 changed files with 232 additions and 7 deletions

View File

@ -0,0 +1,118 @@
//
// PushHandler.swift
// AIGrammar
//
// Created by oscar on 2024/8/31.
//
import UIKit
import SwiftUI
import UserNotifications
enum PromotionDisplayType {
case halfScreen
case fullScreen
case urlLink(String) // URL URL
}
class NofifyState: ObservableObject {
@Published var selectedTab: Int = 0
@Published var showPromotion: Bool = false
@Published var promotionMode: PromotionDisplayType = .halfScreen
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// AIGrammarApp
var app: AIGrammarApp?
var window: UIWindow?
var rootView: ContentView?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// UNUserNotificationCenter delegate
UNUserNotificationCenter.current().delegate = self
//
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
logger.info("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
logger.info("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
logger.info("Device Token: \(token)")
// token
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
logger.error("Failed to register: \(error)")
}
/*
//
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
logger.info("get push msg in willPresent")
globalEnvironment.pushSettings.appAtFront = true
//completionHandler([.sound, .banner])
}
*/
//
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
logger.info("get push msg in didReceive")
let userInfo = response.notification.request.content.userInfo
//
globalEnvironment.pushSettings.gotoTab = extractValue(from: userInfo, key: "gotoTab", defaultValue: 0, logMessage: "gotoTab not found or invalid in userInfo")
globalEnvironment.pushSettings.showPage = extractValue(from: userInfo, key: "showPage", defaultValue: 0, logMessage: "showPage not found or invalid in userInfo") != 0
globalEnvironment.pushSettings.page = extractValue(from: userInfo, key: "page", defaultValue: "", logMessage: "page not found or invalid in userInfo")
globalEnvironment.pushSettings.showMode = extractValue(from: userInfo, key: "showMode", defaultValue: "", logMessage: "showMode not found or invalid in userInfo")
globalEnvironment.pushSettings.openURL = extractValue(from: userInfo, key: "url", defaultValue: "", logMessage: "url not found or invalid in userInfo")
//
if globalEnvironment.pushSettings.appAtFront {
DispatchQueue.main.async {
self.app?.handlePushNotification()
}
globalEnvironment.pushSettings.appAtFront = false
}
completionHandler()
}
// userInfo
func extractValue<T>(from userInfo: [AnyHashable: Any], key: String, defaultValue: T, logMessage: String) -> T {
if let value = userInfo[key] as? T {
return value
} else {
logger.info(logMessage)
return defaultValue
}
}
}
struct PromotionView: View {
var body: some View {
Text("This is the Promotion View")
}
}