2015-12-07 116 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应该非常简单。