2015-12-07 112 views

回答

11

我對您準備了一些剪斷代碼示出了具有一個按鈕10第二通知沒有示出ViewDidLoad方法之後。

import UIKit 

    class TestViewController: UIViewController { 

     let category = UIMutableUserNotificationCategory() 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      let restartAction = UIMutableUserNotificationAction() 
      restartAction.identifier = "xx" 
      restartAction.destructive = false 
      restartAction.title = "Restart" 
      restartAction.activationMode = .Background 
      restartAction.authenticationRequired = false 

      let categoryIdentifier = "category.identifier" 
      category.identifier = categoryIdentifier 
      category.setActions([restartAction], forContext: .Minimal) 
      category.setActions([restartAction], forContext: .Default) 

      let categories = Set(arrayLiteral: category) 
      let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: categories) 
      UIApplication.sharedApplication().registerUserNotificationSettings(settings) 


      let localNotif = UILocalNotification() 
      localNotif.alertBody = "testBody" 
      localNotif.category = categoryIdentifier 

      // Notification will be shown after 10 second (IMPORTANT: if you want to see notification you have to close or put app into background) 
      localNotif.fireDate = NSDate().dateByAddingTimeInterval(10) 
      UIApplication.sharedApplication().scheduleLocalNotification(localNotif) 
     } 

    } 

注意:你必須處理在AppDelegate的方法操作:

func application(application: UIApplication, handleActionWithIdentifier identifier: String?, 
       forLocalNotification notification: UILocalNotification, completionHandler:() -> Void) { 

    completionHandler() 
} 

當然我的代碼是不是乾淨,因爲它應該是,但你要知道,我寫的只爲呈現目的。

此代碼是用Swift編寫的,但是轉換爲Objective C應該非常簡單。