2016-02-07 25 views
2

我的事件日期輸出正確,我的頁面沒有錯誤,但是我的應用崩潰了,請幫忙?如何爲UILocalNotifiication設置NSDate

我認爲它可能有一些與我的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) 
+0

有很多奇怪的可選事情正在進行。例如,'(date as?NSDate)!'非常有趣。爲什麼不使用'date as! NSDate'?此外,字符串不能簡單地鑄造日期。他們必須通過'NSDateFormatter'的'dateFromString:'方法。 – tktsubota

回答

0

有很多錯誤。

首先,您不能簡單地將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) 

希望這有助於。 :)