您好,登錄后才能下訂單哦!
要在SwiftUI中實現本地通知,可以使用UserNotifications框架。首先,需要在AppDelegate.swift文件中請求用戶授權發送通知:
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("User has granted permission for notifications")
} else {
print("User has denied permission for notifications")
}
}
UNUserNotificationCenter.current().delegate = self
return true
}
}
然后,在需要發送通知的地方,可以使用以下代碼來創建和發送通知:
import UserNotifications
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "Don't forget to do your tasks!"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "reminderNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error adding notification: \(error)")
}
}
確保在發送通知之前,在Info.plist文件中添加以下權限:
這樣就可以在SwiftUI中實現本地通知了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。