// // AppDelegate.swift // copinism // // Created by 黄仕杰 on 2024/6/7. // import UIKit import UserNotifications class AppDelegate: UIResponder, UIApplicationDelegate { //当应用程序启动后,可能需要进行其他逻辑处理时调用的方法 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 请求推送通知权限 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } } return true } /// 当设备成功注册推送通知时调用。用来获取设备令牌并发送到服务器 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // 获取 deviceToken let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") // 将 deviceToken 发送到服务器 sendDeviceTokenToServer(token: token) } // 当设备未能注册推送通知时调用。用来处理和记录错误信息 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } private func sendDeviceTokenToServer(token: String) { // 服务器的 API URL let url = URL(string: "https://yourserver.com/api/deviceToken")! // 设备信息 let parameters: [String: Any] = [ "deviceToken": token, "deviceType": "iOS" ] // 使用 URLSession 发送请求 var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try? JSONSerialization.data(withJSONObject: parameters) let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error sending device token: \(error)") return } print("Device token sent successfully") } task.resume() } }