无法从通知中获得变量?

问题描述 投票:0回答:1

我想写一个项目有一个通知可以打印存储在主viewcontroller中的数据,但是当通知被触发时,总是得到空数据。

在ViewController中

arrPerson = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    arrPerson.append("Peter")
    arrPerson.append("Jack")

setNotification()
}

func printTheName() {
    print("In printTheName")
    print("arrPerson:\(arrPerson.count)")
    for x in arrPerson {
        print(x)
    }
}

func setNotification() {

    let notification = UNMutableNotificationContent()
    notification.title = "title"
    notification.subtitle = ""
    notification.body = "body"
    notification.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

    let request = UNNotificationRequest(identifier: "check", content: notification, trigger: trigger)

    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.add(request) { (error) in
        if error != nil {
            print("notificationCenter.add ERROR:\(error)")
            // Handle any errors.
        }
    }
}

在Appdelegate

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("In userNotificationCenter")
    ViewController().printTheName()
}

代码将打印出“userNotificationCenter”,“in printTheName”,“arrPerson:0”。

我需要从通知中获取数据。从通知中调用printTheName时为什么arrPerson.count为0?

xcode swift4 appdelegate
1个回答
0
投票

尝试使用appdelegate中的窗口以编程方式实例化viewController。您可以在通知中心获取计数。或者因为您的viewController类是登陆屏幕,所以在主类中调用userNotifationCenter方法而不是在此处。

© www.soinside.com 2019 - 2024. All rights reserved.