【问题标题】:How to set NSDate for UILocalNotifiication如何为 UILocalNotification 设置 NSDate
【发布时间】:2016-02-07 14:27:33
【问题描述】:

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

我相信这可能与将我的 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)

【问题讨论】:

  • 发生了很多奇怪的可选事情。例如,(date as? NSDate)! 非常有趣。为什么不使用date as! NSDate?此外,字符串不能简单地转换为日期。他们必须通过NSDateFormatterdateFromString:方法。

标签: swift nsdate uilocalnotification


【解决方案1】:

有很多错误。

首先,您不能简单地将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)

希望这会有所帮助。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多