我已在 didFinishLaunchingWithOptions
中添加了这些内容let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
self.createLocalNotification()
然后,调用以下功能。
func createLocalNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
// localNotification.applicationIconBadgeNumber = 1
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = [
"id": "not_id0",
"message": "Check notification"
]
localNotification.alertBody = "Check notification"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
要取消此通知,我已在 didReceiveLocalNotification 中尝试过,但每次启动App时仍会显示通知。
let app:UIApplication = UIApplication.sharedApplication()
for oneEvent in app.scheduledLocalNotifications! {
let notification = oneEvent as UILocalNotification
let userInfoCurrent = notification.userInfo! as! [String:AnyObject]
let id = userInfoCurrent["id"]! as! String
if id == "not_id0" {
//Cancelling local notification
app.cancelLocalNotification(notification)
break;
}
}
如何创建首次本地通知?如果有人解释它会很棒。
答案 0 :(得分:1)
在userDefaults中添加标志,然后检查是否
NSUserDefaults.standardUserDefaults().boolForKey("notified")
如果没有,打开通知方法,那里
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notified")
答案 1 :(得分:1)
您可以使用NSUserDefaults
:
didFinishLaunchingWithOptions:
中的AppDelegate
:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
if let haveShownFirstRunNotification = NSUserDefaults.standardUserDefaults().boolForKey("haveShownFirstRunNotification") {
if !haveShownFirstRunNotification {
createLocalNotification()
}
}
...
}
在createLocalNotification
:
func createLocalNotification() {
...
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "haveShownFirstRunNotification")
}