fix notif

This commit is contained in:
anlicheng 2025-04-03 16:37:37 +08:00
parent e775ee2421
commit 4226476d3a
2 changed files with 150 additions and 0 deletions

View File

@ -36,6 +36,24 @@ struct API {
//
static let baseUrl = "https://dimensionhub.s5s8.com"
// token
static func sendDeviceTokenToServer<T: Codable>(userId: String, token: String, as: T.Type) async -> APIResponse<T> {
// Create the request
var request = URLRequest(url: URL(string: baseUrl + "/api/device_token")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Convert parameters to JSON data
let parameters: [String:String] = [
"user_id": userId,
"token": token
]
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = jsonData
return await doRequest(request: request, as: T.self)
}
//
static func getIndexData<T: Codable>(userId: String, as: T.Type) async -> APIResponse<T> {
let request = URLRequest(url: URL(string: baseUrl + "/api/index?user_id=\(userId)")!)

View File

@ -10,6 +10,8 @@ import SwiftData
@main
struct dimensionhubApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
@ -48,3 +50,133 @@ struct dimensionhubApp: App {
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self
//
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {granted, error in
print("通知权限 granted: \(granted)")
guard granted else {
return
}
//
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("通知设置: \(settings)")
guard settings.authorizationStatus == .authorized else {
return
}
print("通知设置: authorized!!!!")
DispatchQueue.main.async {
//
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
// deviceToken
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// deviceToken
Task {
guard let userId = UserDefaults.standard.string(forKey: "userId") else {
return
}
let sendResult = await API.sendDeviceTokenToServer(userId: userId, token: token, as: String.self)
switch sendResult {
case .result(let reply):
NSLog("send token to server get reply: \(reply)")
case .error(let errorCode, let message):
NSLog("send token to server error_code: \(errorCode), message: \(message)")
}
}
}
//
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("注册远程通知失败: \(error)")
}
// App
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//
handleRemoteNotification(userInfo: userInfo)
completionHandler(.newData)
}
private func handleRemoteNotification(userInfo: [AnyHashable: Any]) {
print("收到远程通知: \(userInfo)")
//
if let aps = userInfo["aps"] as? [String: AnyObject] {
if let alert = aps["alert"] as? String {
print("通知消息: \(alert)")
}
//
if let customData = userInfo["customData"] as? [String: AnyObject] {
print("自定义数据: \(customData)")
}
}
}
}
//
extension AppDelegate: UNUserNotificationCenterDelegate {
// App
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
//
handleRemoteNotification(userInfo: userInfo)
//
completionHandler([.banner, .sound])
}
//
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
//
handleRemoteNotification(userInfo: userInfo)
//
if let deepLink = userInfo["deepLink"] as? String {
handleDeepLink(deepLink)
}
completionHandler()
}
private func handleDeepLink(_ link: String) {
//
print("处理深度链接: \(link)")
}
}