安排本地通知swift4 [英] Schedule local notification swift4

查看:56
本文介绍了安排本地通知swift4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天17:00通过swift4发出本地通知.并且我希望该通知不会在节假日(周六,周日)显示.我该怎么办?

I've made a local notification with swift4 every day every at 17.00. and I want the notification to not show up on holidays (Saturday, Sunday). How can I do that?

这是我的代码:

// schedule notification every day
        var dateComponents = DateComponents ()
        dateComponents.hour = 17
        dateComponents.minute = 00
        dateComponents.day = 7
        let trigger = UNCalendarNotificationTrigger (dateMatching: dateComponents, repeats: true)
        let request = UNNotificationRequest.init (identifier: "Everyday", content: content, trigger: trigger)

推荐答案

func createDate(weekday: Int, hour: Int, minute: Int, year: Int)->Date{

    var components = DateComponents()
    components.hour = hour
    components.minute = minute
    components.year = year
    components.weekday = weekday // sunday = 1 ... saturday = 7
    components.weekdayOrdinal = 10
    components.timeZone = .current

    let calendar = Calendar(identifier: .gregorian)
    return calendar.date(from: components)!
}

//Schedule Notification with weekly bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

    let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date)

    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

    let content = UNMutableNotificationContent()
    content.title = titles
    content.body = body
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "todoList"

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

    UNUserNotificationCenter.current().delegate = self
    //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print(" We had an error: \(error)")
        }
    }
}

这篇关于安排本地通知swift4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆