环境配置:VMware+iOS 14.5+Xcode 12+SwiftUI 记录一下SwiftUI发送通知的代码(因为项目的原因所以没放全部的代码,意会一下
因为在建立项目的时候Life Cycle选的是swiftui app,所以项目中没有AppDelegate.swift文件,需要自己新建一个
import Foundation
import UIKit
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound], completionHandler: {(success, error) in
if success{
print("success")
}
if error != nil{
print("error")
}
})
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
clearBadge()
guard let trigger = notification.request.trigger else { return; }
receiveNotification(flag: "willPresent", trigger: trigger)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
clearBadge()
guard let trigger = response.notification.request.trigger else { return; }
receiveNotification(flag: "did receive", trigger: trigger)
}
func receiveNotification(flag: String, trigger: UNNotificationTrigger) {
if trigger.isKind(of: UNTimeIntervalNotificationTrigger.classForCoder()) {
print("Notification \(flag), Is class UNTimeIntervalNotificationTrigger")
} else if trigger.isKind(of: UNCalendarNotificationTrigger.classForCoder()) {
print("Notification \(flag), Is class UNCalendarNotificationTrigger")
}
}
func clearBadge() {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
然后需要在App.swift文件里修改一下(不同项目swift文件名不同,需要找一下,主要改的是有@的那句
import SwiftUI
import UIKit
import UserNotifications
@main
struct App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
然后是NotificationFunc.swift用来放发送通知和撤回通知的函数(撤回通知的函数没用上,酌情使用
import Foundation
import UserNotifications
let NotificationContent = UNMutableNotificationContent()
func sendNotification(){
NotificationContent.title = "testContent"
NotificationContent.body = "test"
NotificationContent.sound = UNNotificationSound.default
NotificationContent.badge = 1
var matchingDate = DateComponents()
matchingDate.hour = 19
matchingDate.minute = 52
print("matchingDate:\(matchingDate)")
let trigger = UNCalendarNotificationTrigger(dateMatching: matchingDate, repeats: true)
let request = UNNotificationRequest(identifier: NotificationContent.title + matchingDate.description, content: NotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { err in
err != nil ? print("添加本地通知错误", err!.localizedDescription) : print("添加本地通知成功")
}
}
func widthdrawNotification(clockset:ClockSet){
let timeNotification = string2Date(clockset.content)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [clockset.content + timeNotification.description])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [clockset.content + timeNotification.description])
}
最后是发送通知UI界面,这里没写全,意会一下
Text("发送通知")
.onAppear(){ UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]){_,_ in
sendNotification()
}
}
这样就可以发送通知了! 不过我在虚拟机上运行的时候发送的挺慢的,几乎要等设定时间的下一分钟才发过来,想要见效快的可以试试改一下NotificationFunc.swift,蓝色线的代码删除,红色字代码替换,红色字代码的意思是每一分钟的第五秒就会发送通知。
|