我有一个有效的预定通知,我正在尝试从该通知中获取信息以打开另一个视图,但现在我无法在代码的
onReceive
部分中将该信息传递到我的主视图中。
我可以在代码的
AppDelegate
部分看到信息。
我觉得我在某处遗漏了一小步。
tl;dr:尝试将通知信息从
AppDelegate
传递到 MainView
@main
struct UntitledNewsApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var notificationData = NotificationData()
var body: some Scene {
WindowGroup {
MainView()
.environmentObject(notificationData)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var notificationData = NotificationData()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Handle the received notification and navigate to the desired view
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
let articleResponse = response.notification.request.content
notificationData.notificationTitle = articleResponse.title
DispatchQueue.main.async {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.notificationData.notificationTitle = articleResponse.title
}
}
// Notification tapped, navigate to the desired view
NotificationCenter.default.post(name: NSNotification.Name("NotificationTapped"), object: nil)
}
completionHandler()
}
}
class NotificationData: ObservableObject {
@Published var notificationTitle: String = ""
}
struct MainView: View {
@EnvironmentObject var notificationData: NotificationData
...
var body: some View {
Text("Never Give You Up")
.onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("NotificationTapped"))) { notification in
print("onReceive in blank: \(notificationData.notificationTitle)")
}
}
}
每次调用
NotificationData()
时,您都会创建一个不同的实例,其中一个实例不知道另一个实例。
您可以更改注射方式进行连接。
.environmentObject(appDelegate.notificationData)
您不需要
@StateObject
,AppDelegate
将管理生命周期。