【问题标题】:iOS Local notificationsiOS 本地通知
【发布时间】:2020-04-08 05:37:29
【问题描述】:

我正在尝试每 1 分钟触发一次本地通知,即使在终止状态和后台状态下也是如此。但是,当时间在下午 06:00 之后,我的应用程序不应触发通知。下面是我的代码。

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,repeats: true)
    //UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    // Create the request
    let uuidString = UUID().uuidString
    let request = UNNotificationRequest(identifier: uuidString,
                content: content, trigger: trigger)

    // Schedule the request with the system.
    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.add(request) { (error) in
       if error != nil {
          // Handle any errors.
       }
    }
}

【问题讨论】:

    标签: ios swift uilocalnotification


    【解决方案1】:

    要处理本地通知,试试这个:

    public func addLocalNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
        // Initialize
         let center = UNUserNotificationCenter.current()
    
       // Set its content
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.sound = .default
    
        // whenever you want to notify user select time
        var dateComp = DateComponents()
        dateComp.calendar = Calendar.current 
        dateComp.hour = hour
        dateComp.minute = minute
    
        // repeat and date
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
    
        // Initializing the Notification Request object
        let req = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    
        // Add the notification to the center
        center.add(req) { (error) in
            if (error) != nil {
                print(error!.localizedDescription)
            }
        }
    }
    

    【讨论】:

    • 这正是我的代码所做的,除了您所做的日期操作。例如,我要求不要在下午 6 点之后触发它。即,如果我的应用程序被终止,我也需要这样做。
    • 获取下午6点的时间,并告诉用户通知中心“removeAllPendingNotificationRequests”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多