2016-07-18 42 views
0

我在didFinishLaunchingWithOptionsSwift - 如何创建第一次应用程序启动本地通知?

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下面尝试,但仍然显示通知每一个应用程序启动。

 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; 
      } 
     } 

如何创建第一次本地通知?如果有人解释这将是伟大的。在userDefaults和

回答

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") 
} 
1

添加标志,则检查是否

NSUserDefaults.standardUserDefaults().boolForKey("notified") 

如果不是,开封通知方法,有将

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notified") 
相关问题