如何快速设置每周本地通知 [英] How to set a weekly local notification in swift

查看:99
本文介绍了如何快速设置每周本地通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有问题.

我想在xcode7中设置本地通知,我正在开发一个日历,您可以在其中放置大学的课程,但事实是我要从json数据库获取日程安排,并且我想在15分钟前通知课程开始,但是我不知道为什么我的代码无法正常工作.

I want to set a local notification in xcode7, I'm developing a calendar where you can put your university's courses, the thing is that I'm getting the schedule from a json database and I want to notify 15 min before the class starts, but I do not know why my code is not working.

这是一个示例,我想在每个星期一的13:40重复通知.

This is an example where I want to repeat the notification every Monday at 13:40.

我只能设置日期和时间吗?还是也应该指定月份和年份?

Can I only set the day and the hour? or should I specify the month and the year too?

  var dateComp:NSDateComponents = NSDateComponents()

    dateComp.day = 01;
    dateComp.hour = 13;
    dateComp.minute = 40;
    dateComp.timeZone = NSTimeZone.systemTimeZone()

    var calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    var date:NSDate = calender.dateFromComponents(dateComp)!

    let notification = UILocalNotification()
    notification.fireDate = date
    notification.alertBody = "Swipe to unlock"
    notification.alertAction = "You've got a class soon!"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["CustomField1": "w00t"]
    notification.repeatInterval = NSCalendarUnit.WeekOfYear

    UIApplication.sharedApplication().scheduleLocalNotification(notification)

推荐答案

**迅速的每周本地通知4

**Weekly Local notification for swift 4

let content = UNMutableNotificationContent()
    content.title = "LocalNotification"
    content.subtitle = "notify"
    content.body = "I am Text"
    content.categoryIdentifier = "alarm"
    content.badge = 1
    content.sound = UNNotificationSound.default()

//配置重复日期.

    var dateComponents = DateComponents()
    dateComponents.calendar = Calendar.current

    dateComponents.weekday = 3
    dateComponents.hour = 13
    dateComponents.minute = 10

    // Create the trigger as a repeating event.
    let trigger = 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.
            print("************Error***************")
        }
    }
}

这篇关于如何快速设置每周本地通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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