You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 15:06:03