2016-02-18 113 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