如何使用swift创建本地通知?

时间:2016-09-21 10:23:47

标签: swift uilocalnotification

我已创建本地通知及其正常工作。但如果我们点击查看通知,那首歌就不会播放,我希望播放这首歌直到用户停止播放。 我希望有一个按钮可以让用户停止播放歌曲。

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
   let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound],  categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    self.generateLocalNotification()
    return true
}

func generateLocalNotification(){

    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    var dateFire=NSDate()

    var fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())

    if (fireComponents.hour >= 9) {
       // dateFire=dateFire.dateByAddingTimeInterval(86400)  // Use tomorrow's date
        fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())
    }
    fireComponents.hour = 9
    fireComponents.minute = 0
    dateFire = calendar.dateFromComponents(fireComponents)!
    let localNotification = UILocalNotification()
    localNotification.fireDate = dateFire
    localNotification.repeatInterval = NSCalendarUnit.Day
    localNotification.timeZone = NSCalendar.currentCalendar().timeZone
    localNotification.alertBody = " Started!"
    localNotification.alertAction = "hear the song!"
    localNotification.soundName = "jingle-bells-sms.m4r"
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {

        let alertMessage = UIAlertController(title: "NAME", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)

        let image = UIImage(named: "1_flash")

        let action = UIAlertAction(title: "STOP", style: UIAlertActionStyle.Cancel, handler:nil)
         action.setValue(image, forKey: "image")
 alertMessage.addAction(action)
        self.window?.rootViewController?.presentViewController(alertMessage, animated: true, completion: nil)

    }

    else
    {
}

1 个答案:

答案 0 :(得分:0)

您的声音文件只能播放30秒。然后你必须设置重复本地通知,在重复模式下播放30秒的声音文件。

请查看Apple文档。

https://developer.apple.com/reference/uikit/uilocalnotification