ios - 如何按小时和日期显示本地议程或本地通知

标签 ios arrays swift uilocalnotification nsnotificationcenter

我有这个数组,它已经填充在带有动态单元格的表格 View 中,我想要它创建一个本地议程或通知或警报或类似的东西,以提醒用户在显示的日期和时间吃药在数组中,你能帮我吗?请。多谢。

{“medicine”:”paracetamol”

        “day”:”tuesday”

        “time”:”9:00”},

         {“medicine”:”aspirine”

        “day”:”friday”

        “time”:”16:00”},

         {“medicine”:”pills”

        “day”:”monday”

        “time”:”22:00”}

最佳答案

您必须创建一个日历对象,并在 comps.weekday、comps.hour 和 comps.min 属性中设置工作日和时间值。

对于您的消息,请在通知 content.body 属性中设置。

import UserNotifications

let calendar = NSCalendar.init(calendarIdentifier: .gregorian)
calendar?.locale = NSLocale.current

let year = calendar?.component(.year, from: date)
let month = calendar?.component(.month, from: date)

let cal = Calendar.current
var comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: date)
comps.weekday = i // Monday - Friday
comps.hour = j
comps.minute = minute
comps.year = year
comps.month = month

let notificationDate = cal.date(from: comps)!
let interval = String.init(format: "%d%d%d", i,j,minute)


if #available(iOS 10.0, *) {

    let triggerDate =  Calendar.current.dateComponents([.weekday,.hour,.minute], from: notificationDate as Date)

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

    let content = UNMutableNotificationContent()
    content.title = DataManager.sharedInstance.notificationTitle
    content.body = String.init(format: "%@", DataManager.sharedInstance.notificationMessage)
    content.sound = UNNotificationSound.default()

    let request = UNNotificationRequest(identifier: String(interval), content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print(error)
        }
    }

} else {
    // ios 9


    // Fallback on earlier versions
    let notification = UILocalNotification()

    /* Time and timezone settings */
    notification.fireDate = date
    notification.repeatInterval = NSCalendar.Unit.weekday
    notification.timeZone = NSCalendar.current.timeZone
    notification.alertBody = "message"

    notification.userInfo = [ "title" : String(interval)]

    /* Schedule the notification */
    UIApplication.shared.scheduleLocalNotification(notification)
}

更新答案

  1. 将您的 json 转换为 NSDictionary 对象的 NSArray。使用 NSJSonSerialization 类。
  2. 对 NSArray 实例运行 for 循环并逐个访问 NSDictionary 对象。
  3. 使用 NSDictionary valueForKey 方法。传递键名并从字典中获取值。

关于ios - 如何按小时和日期显示本地议程或本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873174/

相关文章:

ios - 如果用户执行除删除操作以外的任何事件,则向后滑动 tableView 行 "Delete Row"选项

iphone - 加载较小图像表示的最有效方法

c - "Expected expression before ' { ' token"

javascript - For 语句打破循环

javascript - 在Javascript中打印出子数组的元素

swift - 如何使用 Swift 在 FireBase 数据库中发生更改时获取计数值?

ios - viewDidLoad 中的代码在每次调用时运行

ios - 网络扩展 IPC 中的奇怪崩溃

ios - TabController 上的 ContainerView 创建 Phantom Tab

ios - 使用APNs推送服务时 "keyID"是什么