NotificationSection.swift (3312B)
1 // 2 // NotificationSection.swift 3 // txtodo 4 // 5 // Created by FIGBERT on 8/6/20. 6 // 7 8 import SwiftUI 9 import UserNotifications 10 11 struct NotificationSection: View { 12 @AppStorage("notifications") var notificationsEnabled: Bool = false { willSet { 13 if !newValue { 14 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 15 } else { 16 enableNotifications() 17 } 18 } } 19 @AppStorage("notificationID") var notificationID: String = "unset" 20 @AppStorage("notificationTime") var notificationTime: Int = 0 { willSet { enableNotifications() } } 21 22 var body: some View { 23 Section { 24 Toggle(isOn: $notificationsEnabled) { 25 #if os(iOS) 26 Label(notificationsEnabled ? "notifications enabled" : "notifications disabled", systemImage: "app.badge") 27 #else 28 Text("txtodo notifications \(notificationsEnabled ? "enabled" : "disabled")") 29 #endif 30 } 31 if self.notificationsEnabled { 32 HStack { 33 Label("time scheduled", systemImage: "clock") 34 Spacer() 35 Picker( 36 selection: $notificationTime, 37 label: Text("notification time"), 38 content: { 39 Text("8:30").tag(0) 40 Text("9:30").tag(1) 41 Text("10:30").tag(2) 42 }) 43 .labelsHidden() 44 .pickerStyle(SegmentedPickerStyle()) 45 } 46 } 47 } 48 } 49 50 func enableNotifications() { 51 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 52 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { success, error in 53 if success { 54 let content = UNMutableNotificationContent() 55 content.title = String(format: NSLocalizedString("open txtodo", comment: "")) 56 content.body = String(format: NSLocalizedString("take some time to plan your day", comment: "")) 57 content.sound = UNNotificationSound.default 58 var time = DateComponents() 59 if self.notificationTime == 0 { 60 time.hour = 8 61 } else if self.notificationTime == 1 { 62 time.hour = 9 63 } else { 64 time.hour = 10 65 } 66 time.minute = 30 67 let trigger = UNCalendarNotificationTrigger( 68 dateMatching: time, 69 repeats: true 70 ) 71 let id = UUID().uuidString 72 self.notificationID = id 73 let request = UNNotificationRequest( 74 identifier: id, 75 content: content, 76 trigger: trigger 77 ) 78 UNUserNotificationCenter.current().add(request) 79 } else if let error = error { 80 print(error.localizedDescription) 81 } 82 } 83 } 84 } 85 86 struct NotificationSection_Previews: PreviewProvider { 87 static var previews: some View { 88 NotificationSection() 89 } 90 }