在用户每天选择Swift的时候,是否还要触发UILocalNotification?

时间:2015-01-24 02:25:27

标签: ios swift ios8 uilocalnotification

我正在构建一个应用程序,需要在用户通过UIDatePicker设置时每天显示通知。

我的代码来自here

@IBOutlet var myDatePicker: UIDatePicker!
@IBOutlet var mySwitch: UISwitch!

var localNotification = UILocalNotification()   // You just need one
var notificationsCounter = 0

// put your functions now
func datePicker()            { myDatePicker.datePickerMode = UIDatePickerMode.Time }
func notificationsOptions()  {
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = .CalendarUnitDay
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    localNotification.alertAction = "Open App"
    localNotification.alertBody = "Here is the seven o'clock notification"
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    //     you may add arbitrary key-value pairs to this dictionary.
    //     However, the keys and values must be valid property-list types
    //     if any are not, an exception is raised.
    // localNotification.userInfo = [NSObject : AnyObject]?
}
func toggleSwitch(){
    if mySwitch.on{
        localNotification.fireDate = myDatePicker.date
    } else {
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999)   // will never be fired
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    datePicker()
    notificationsOptions()
    // Do any additional setup after loading the view, typically from a nib.
}

// here is where you place your IBActions

@IBAction func switchPressed(sender: AnyObject) {
    toggleSwitch()
}

但它没有用。

2 个答案:

答案 0 :(得分:1)

由我自己解决。我不小心将dateFormatter.dateFormat = "HH:mm:ss"设置为错误。

答案 1 :(得分:0)

您可以将日期和时间从date picker传递到以下代码,

NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
//Pass here your values
[comps setDay:1]; 
[comps setMonth:1];
[comps setYear:2013];
[comps setHour:10];
[comps setMinute:10];
[comps setSecond:10];
localNotification.fireDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

希望这段代码可以帮到你。