变量
@State var notificationsOn: Bool = false
功能
func pushEnabledAtOSLevel(){
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .denied {
// Notifications are allowed
let content = UNMutableNotificationContent()
content.title = "Elini Yıka"
content.subtitle = "Çabuk ol git! Elini Yıka!"
content.sound = UNNotificationSound.default
// show this notification five seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
//self.notificationsOn = true
}
else {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
//MARK: - Toogle'ın değiştiği yer.
print("Bildirimlere izin verildi.")
//Toggle'ıdeğiştirdiğim yer burası.
self.notificationsOn = true
} else if let error = error {
print("Bildirimler kapalı.")
print(error.localizedDescription)
//Toggle'ıdeğiştirdiğim yer burası.
self.notificationsOn = false
}
}
}
}
}
Toggle
Toggle(isOn: $notificationsOn) {
Text("Bildirimler")
.font(.system(size: 17, design: .rounded))
}
我尝试使用willset和didset触发变量,但没有。当我关闭切换时,通知将关闭。当我打开Toggle时,它会征求许可并打开通知。我做不到。
@State var notificationsOn = false
var body: some View {
let toggle = Binding<Bool> (
get: { self.notificationsOn },
set: { newValue in
self.notificationsOn = newValue
// Do more stuff here.
}
})