【问题标题】:toggle to get notified in swiftui切换以在 swiftui 中获得通知
【发布时间】:2021-07-28 03:10:47
【问题描述】:

我希望能够在每天的特定时间通知用户我的应用。在这个例子中,时间是中午

import SwiftUI
import UserNotifications

struct Alert: View {
    
    @State var noon = false
    
    
    func noonNotify() {
        
        let content = UNMutableNotificationContent()
        content.title = "Meds"
        content.subtitle = "Take your meds"
        content.sound = UNNotificationSound.default
        
        
        var dateComponents = DateComponents()
        dateComponents.hour = 14
        dateComponents.minute = 38
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
        
        // choose a random identifier
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        
        // add our notification request
        UNUserNotificationCenter.current().add(request)
        
        
        
    }
    
    
    
    var body: some View {
        
        
        VStack {
            
            Toggle(isOn: $noon) {
                Text("ThirdHour")
            }
            
            if noon {
                noonNotify()
            }
            
            Button("Request Permission") {
                
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                    if success {
                        print("All set!")
                    } else if let error = error {
                        print(error.localizedDescription)
                    }
                }
                
                
            }
             
        }
    }
}

我创建了一个函数,当切换为真时,函数将执行,但当它为假时,它不会执行。但是,当我创建一个 if 语句时,我得到一个错误

类型'()'不能符合'View';只有结构/枚举/类类型可以符合协议

谁能解释我做错了什么?

【问题讨论】:

    标签: xcode swiftui xcode12


    【解决方案1】:

    你不能调用这样的函数。 var body: some View { 中的所有内容都必须是 View,并且 noonNotify() 不会返回 View

    相反,添加一个onChange 块,每当noon 更改时都会触发该块。

    Toggle(isOn: $noon) {
        Text("ThirdHour")
    }
    .onChange(of: noon) { newValue in
        if newValue {
            noonNotify()
        }
    }
    

    【讨论】:

    • 我在我的资产中添加了一个 mp3 声音,并希望将其用作我的通知声音。我将此添加到我的代码中,但它不起作用,它只是听起来默认声音 ``` content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.mp3")) ``` 你会碰巧知道怎么做那也是?
    • @CodeBeast 我从未使用过通知。但你应该把它作为一个新问题发布
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2021-10-28
    • 2021-06-23
    相关资源
    最近更新 更多