swift - 如何为 UILocalNotifiication 设置 NSDate

标签 swift nsdate uilocalnotification

我的事件日期输出正确,我的页面没有错误,但我的应用程序崩溃了,请帮忙?

我相信这可能与将我的 NSString 日期转换为 NSDate 有关

NSLog("This is the EventDate: \(eventdate)")
    let date = eventdate as? NSString



    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
    var DateInFormat = dateFormatter.stringFromDate((date as? NSDate)!)

    var notification:UILocalNotification = UILocalNotification()
    notification.alertBody = "\(eventtitle) is about to start at the \(rsPubName)"
    notification.category = "FIRST_CATEGORY"
    notification.alertAction = "heyaaa"
    notification.fireDate = date as? NSDate!


    NSLog("This is the date: \(date)")
    UIApplication.sharedApplication().scheduleLocalNotification(notification)

最佳答案

有很多错误。

首先,您不能简单地将 NSString 转换为 NSDate,反之亦然。您需要使用 NSDateFormatter() 提供的函数,例如 dateFromString()stringFromDate()

其次,当您没有在代码中的任何地方使用 DateInFormat 时,为什么要这样做?

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
var DateInFormat = dateFormatter.stringFromDate((date as? NSDate)!)

第三,尝试使用类似这样的东西来设置日期:

let calendar = NSCalendar.currentCalendar()
            let calendarComponents = NSDateComponents()
            calendarComponents.hour = 8
            calendarComponents.second = 0
            calendarComponents.minute = 0
            calendarComponents.day = 1
            calendarComponents.year = 2015
            calendarComponents.month = 2
            let dateToFire = calendar.dateFromComponents(calendarComponents)

希望这对您有所帮助。 :)

关于swift - 如何为 UILocalNotifiication 设置 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254675/

相关文章:

ios - 在 Swift 中捕获闭包值

swift - Firebase snapshot.key 不返回实际 key ?

ios - 用户界面 TableView : Nested Header sections

ios - 如何将 NSDate 的秒数设置为零

ios - Swift Realm 使用数组过滤 List 属性

ios - NSCache 无法正常工作,无法从缓存加载图像

iphone - 在 NSArray 中查找具有给定时间(例如晚上 8 点)之后的某个时间的 NSDate?

ios - 如何从不同的函数检索 Realm 对象? swift

iphone - 删除并重新安装 iphone 应用程序后接收本地通知

ios - UILocalNotification 的 alertTitle 属性不起作用