我是iOS技术的新手。我正在尝试使用UILocalNotification使用swift 2.0构建一个警报应用程序。当我点击按钮时,我从UIPickerView获取时间和日期。我也想显示通知和播放声音。 但声音和通知都不起作用。请帮帮我!
@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)
}
答案 0 :(得分:5)
您必须注册本地通知。将其添加到视图控制器:
override func viewDidAppear() {
super.viewDidAppear()
let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
首次显示您的视图时会出现提示,点击“确定”并且您的通知应该有效。请记住,用户始终可以禁用通知。