AppDelegate:只有当一个新的通知,如何调用函数?

时间:2017-04-15 19:12:50

标签: ios swift function notifications

我遇到了问题,因为我的应用程序显然每次应用程序完成启动时调用新的通知功能(在AppDelegate中)。如果我的newNotification() - 函数仅在被用于新通知时被调用,而不是在应用程序开始启动时被调用?

以下是appDelegate(mvc = MainViewController)的相关代码:

  let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    }

    let generalCategory = UNNotificationCategory(identifier: "GENERAL",
                                                 actions: [],
                                                 intentIdentifiers: [],
                                                 options: .customDismissAction)

    center.setNotificationCategories([generalCategory])

    let content = UNMutableNotificationContent()

    mvc.newNotification()

    let contentText = UserDefaults.standard.string(forKey: "contentText")
    content.title = NSString.localizedUserNotificationString(forKey: "The Better Life Challenge", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "\(contentText!)", arguments: nil)

    var dateInfo = DateComponents()
    dateInfo.hour = 4
    dateInfo.minute = 0
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)

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

    center.add(request) { (error : Error?) in
        if let theError = error {
            print(theError.localizedDescription)
        }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你在名为didRecieveRemoteNotification的方法中执行此操作...当你收到新的通知时会激活此方法,而不是didFinishLaunchingWithOptions ..