使用Swift开发iOS通知时出现Value member not found错误如何修复
问题修复方案
错误原因
- 变量名大小写不匹配:Swift语言大小写敏感,你在
Screen中定义的ObservedObject属性名为大写开头的NotificationManager,调用时却使用了小写开头的notificationManager,编译器无法识别对应成员。 - 方法定义位置错误:
sendNotification方法现在被定义在LocalNotificationManager的init方法内部,属于局部函数,类外部无法访问。 - 缺失依赖框架导入:使用
UNUserNotificationCenter等通知相关API需要导入UserNotifications框架,你当前代码未导入。 - 方法参数大小写不匹配:
sendNotification定义的形参名为大写开头的LaunchIn,调用时使用的是小写开头的launchIn,同样会触发参数不匹配错误。
修复后的完整代码
import SwiftUI import Foundation import UserNotifications // 新增导入通知框架 class LocalNotificationManager: ObservableObject { var notifications = [Notification]() init() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted == true && error == nil { print("yay") } else { print("boo") } } } // 把sendNotification方法移到init外部,调整参数为小驼峰符合Swift规范 func sendNotification(title: String, subtitle: String?, body: String, launchIn: Double) { let content = UNMutableNotificationContent() content.title = title if let subtitle = subtitle { content.subtitle = subtitle } content.body = body let trigger = UNTimeIntervalNotificationTrigger(timeInterval: launchIn, repeats: false) let request = UNNotificationRequest(identifier: "demoNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } } struct Screen: View { // 调整属性名为小驼峰,和调用时的命名统一 @ObservedObject var notificationManager = LocalNotificationManager() var body: some View { Button(action: { self.notificationManager.sendNotification(title: "It worked", subtitle: ":D", body: "If you see this text, launching the local notification worked!", launchIn: 5) }) { Text("Test Notification") } } } struct Screen_Previews: PreviewProvider { static var previews: some View { Screen() } }
内容的提问来源于stack exchange,提问作者Soulfire J. Backblaze
相关产品推荐
相关产品推荐

