2016-02-18 63 views
0

我是iOS技术的新手。我试图用UILocalNotification构建一个具有swift 2.0的闹钟应用程序。当我点击按钮时,我从UIPickerView获取时间和日期。我也想显示通知和播放声音。 但声音和通知都不起作用。请帮帮我!scheduleLocalNotification在Swift 2.0中不起作用

@IBOutlet weak var myPickerView: UIDatePicker! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    myPickerView.date = NSDate() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


@IBAction func setAlarmClicked(sender: UIButton) { 
    let dateFormater : NSDateFormatter = NSDateFormatter() 
    dateFormater.timeZone = NSTimeZone.defaultTimeZone() 
    dateFormater.timeStyle = .ShortStyle 
    dateFormater.dateStyle = .ShortStyle 

    let dateTimeString : NSString = dateFormater.stringFromDate(myPickerView.date) 
    print("date is \(dateTimeString)") 

    self.sheduleLocalNotificationWithDate(myPickerView.date) 
} 

@IBAction func cancelAlarmClicked(sender: UIButton) { 

} 

func sheduleLocalNotificationWithDate(fireDate : NSDate){ 
    let localNotification : UILocalNotification = UILocalNotification() 
    localNotification.fireDate = fireDate 
    localNotification.alertBody = "Alert !!!!" 
    localNotification.soundName = "minion.mp3" 

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification) 

} 

回答

4

您必须注册本地通知。添加到您的视图控制器:

override func viewDidAppear() { 

    super.viewDidAppear() 
    let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil) 
    UIApplication.sharedApplication().registerUserNotificationSettings(settings) 

} 

警报将拿出当你的观点似乎是第一次,点击“确定”,您的通知应该工作。请记住,用户可以始终禁用通知。

+0

如果我终止应用程序,它仍然可以工作吗? – Inuyasha

+0

@lnuyasha如果你的意思是通知仍然会触发,那么是的。 – tktsubota

+0

当然,它的工作原理。谢谢!你有我的一天。 – Inuyasha