fix notif
This commit is contained in:
parent
e775ee2421
commit
4226476d3a
@ -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)")!)
|
||||
|
||||
@ -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)")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user