copinism-ios/copinism/AppDelegate.swift
2024-06-07 16:04:27 +08:00

68 lines
2.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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()
}
}