Не можете получить переменную из уведомления? - PullRequest
0 голосов
/ 25 марта 2019

Я хочу написать, в проекте есть уведомление, можно распечатать данные, которые хранятся в главном 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».

Мне нужно получить данные из уведомления. Почему arrPerson.count равен 0 при вызове printTheName из уведомления?

1 Ответ

0 голосов
/ 25 марта 2019

Попробуйте программно создать экземпляр viewController, используя окно в вашем приложении.Затем вы сможете получить счетчик в своем центре уведомлений. Или, поскольку ваш класс viewController является целевым экраном, вызовите метод userNotifationCenter в вашем основном классе, а не здесь.

...