以下只是对本地通知的简单测试,但它适用于iPhone(在iPhone 11 iOS 15.5模拟器上测试(,但不适用于iPad(在iPad第6代15.5模拟器上进行测试(。我还在类似的物理设备上测试了它,同样的情况也发生在真实环境中。
我不知道为什么会发生这种情况,因为这似乎不是UI或屏幕布局问题:
import SwiftUI
struct ContentView: View {
@State var started : Bool = false
@State var requested : Bool = false
@State var id : String = ""
func setLocalNotification()
{
let content = UNMutableNotificationContent()
content.title = "Test Local Notification"
content.subtitle = "Hello"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
id = UUID().uuidString
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
func removeNotification()
{
if (requested)
{
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [id])
}
requested=false;
}
var body: some View {
VStack{
Button("Cancel")
{
removeNotification()
started=false;
}
Spacer()
Button("Engage")
{
if (!started)
{
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("Set!")
} else if let error = error {
print(error.localizedDescription)
}
}
requested=true;
started=true;
setLocalNotification()
}
}.foregroundColor(started ? Color.brown : Color.blue)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
您正在请求通知,请使用成功块调用通知,否则请在权限允许之前complex运行您的setLocalNotification((,第一次启动时不会发生任何事情,但当您第二次运行应用程序时,它会起作用,因为现在您启用了通知。因此,使用成功块调用通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
// set here because if you click allow this will trigger otherwise compiler execute it before allow.
setLocalNotification()
} else if let error = error {
print(error.localizedDescription)
}
}
最小化显示通知的应用程序还将测试的60秒改为5秒
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)