通知展示到本地通知中心

This commit is contained in:
huangshijie 2024-06-07 18:00:03 +08:00
parent ea0e93be12
commit 379cff4c73
3 changed files with 73 additions and 15 deletions

View File

@ -7,30 +7,36 @@
import UIKit import UIKit
import UserNotifications import UserNotifications
import SwiftUI
class AppDelegate: UIResponder, UIApplicationDelegate {
// class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// UNUserNotificationCenter
UNUserNotificationCenter.current().delegate = self
// //
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted { if granted {
DispatchQueue.main.async { DispatchQueue.main.async {
application.registerForRemoteNotifications() application.registerForRemoteNotifications()
} }
} else {
// 使
print("用户拒绝通知权限: \(String(describing: error))")
} }
} }
return true return true
} }
/// //
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// deviceToken
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined() let token = tokenParts.joined()
print("Device Token: \(token)") print("Device Token: \(token)")
// deviceToken
sendDeviceTokenToServer(token: token) sendDeviceTokenToServer(token: token)
} }
@ -40,21 +46,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
} }
private func sendDeviceTokenToServer(token: String) { private func sendDeviceTokenToServer(token: String) {
// API URL
let url = URL(string: "https://yourserver.com/api/deviceToken")! let url = URL(string: "https://yourserver.com/api/deviceToken")!
//
let parameters: [String: Any] = [ let parameters: [String: Any] = [
"deviceToken": token, "deviceToken": token,
"deviceType": "iOS" "deviceType": "iOS"
] ]
// 使 URLSession
var request = URLRequest(url: url) var request = URLRequest(url: url)
request.httpMethod = "POST" request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters) request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
let task = URLSession.shared.dataTask(with: request) { data, response, error in let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error { if let error = error {
print("Error sending device token: \(error)") print("Error sending device token: \(error)")
@ -64,4 +64,60 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
} }
task.resume() task.resume()
} }
//
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if #available(iOS 14.0, *) {
completionHandler([.banner, .sound, .badge])
} else {
completionHandler([.alert, .sound, .badge])
}
}
//
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
//
handleNotification(response.notification)
//
let message = Message(text: response.notification.request.content.body, sender: response.notification.request.content.title, timestamp: "" ,isSelf: true, avatar: "avatar")
sendNotification(for: message)
}
completionHandler()
}
private func handleNotification(_ notification: UNNotification) {
//
if let window = window {
// ContentView
let contentView = ContentView()
// SwiftUI UIViewController
let hostingController = UIHostingController(rootView: contentView)
// rootViewController
if let rootViewController = window.rootViewController {
rootViewController.present(hostingController, animated: true, completion: nil)
} else {
window.rootViewController = hostingController
window.makeKeyAndVisible()
}
}
}
//
private func sendNotification(for message: Message) {
let content = UNMutableNotificationContent()
content.title = message.sender
content.body = message.text
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
} }

View File

@ -17,6 +17,8 @@
</dict> </dict>
<key>NSLocalNotificationUsageDescription <key>NSLocalNotificationUsageDescription
NSLocalNotificationUsageDescription</key> NSLocalNotificationUsageDescription</key>
<string>需要通知权限以便发送新消息通知</string>
<key>NSUserNotificationUsageDescription</key>
<string>需要通知权限以便发送新消息通知</string> <string>需要通知权限以便发送新消息通知</string>
<key>UIBackgroundModes</key> <key>UIBackgroundModes</key>
<array> <array>

View File

@ -19,7 +19,7 @@ let pp = "http://43.136.169.205:9999"
let release = "https://api.flyaha.top" let release = "https://api.flyaha.top"
let apiprefixV1 = local+"/api/v1" let apiprefixV1 = pp+"/api/v1"
var loginApi = "/user/login" var loginApi = "/user/login"