使用swos使用ios的本地通知

时间:2016-05-19 13:14:17

标签: ios swift localnotification

我是swift的新手,我不知道如何实现本地通知我尝试了一些代码,但这并不完全正常,所以任何人都可以使用{{1}帮助在iOS中实现本地通知}?

2 个答案:

答案 0 :(得分:34)

我在这里分享一些例子,

注册本地通知,

@IBAction func registerLocal(sender: AnyObject) {
    let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
}

安排本地通知,

@IBAction func scheduleLocal(sender: AnyObject) {
    let notification = UILocalNotification()
    notification.fireDate = NSDate(timeIntervalSinceNow: 5)
    notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
    notification.alertAction = "be awesome!"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["CustomField1": "w00t"]
    UIApplication.sharedApplication().scheduleLocalNotification(notification)


    guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return }

    if settings.types == .None {
        let ac = UIAlertController(title: "Can't schedule", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
        return
    }

}

它会在5 seconds之后触发本地通知。

希望这会有所帮助:)

答案 1 :(得分:4)

网上有很多教程,你可以谷歌吧。

这是一个教程:http://jamesonquave.com/blog/local-notifications-in-ios-8-with-swift-part-1/

此处还有本地通知的示例:

let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = "Alert!"
notification.alertAction = "open"
notification.hasAction = true
notification.userInfo = ["UUID": "reminderID" ]
UIApplication.sharedApplication().scheduleLocalNotification(notification)