2015-12-09 4 views
0

Я реализовал UILocalNotification в своем приложении с функцией и прекрасно работал, когда приложение работает в фоновом режиме, но когда я полностью закрываю приложение, появляется уведомление, но функция, которая связано с ничего не делать, если кто-нибудь знает, что я сделал не так и как это сделать правильно, чем помочь мнеUILocalNotificationAction не работает после убийства (полностью закрывается) приложение

//AppDelegate.Swift//

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 







    // Override point for customization after application launch. 



    //set up Notifications// 

    //actions 
    //actions for notifications// 
    let firstAction:UIMutableUserNotificationAction = UIMutableUserNotificationAction() 
    firstAction.identifier = "FIRST_ACTION" 
    firstAction.title = "Yes" 

    firstAction.activationMode = UIUserNotificationActivationMode.Background 
    firstAction.destructive = false 
    firstAction.authenticationRequired = false 


    let secondAction:UIMutableUserNotificationAction = UIMutableUserNotificationAction() 
    secondAction.identifier = "SECOND_ACTION" 
    secondAction.title = "No" 
    secondAction.activationMode = UIUserNotificationActivationMode.Background 
    secondAction.destructive = true 
    secondAction.authenticationRequired = false 

    // category 
    let firstCategory: UIMutableUserNotificationCategory = UIMutableUserNotificationCategory() 
    firstCategory.identifier = "FIRST_CATEGORY" 

    let defaultActions:NSArray = [firstAction, secondAction] 
    let minimalActions:NSArray = [firstAction, secondAction] 

    firstCategory.setActions([firstAction, secondAction], forContext: .Default) 
    firstCategory.setActions([firstAction, secondAction], forContext: .Minimal) 

    //NSSET Of all Our Category 
    let categories:NSSet = NSSet(objects: firstCategory) 

    //asking permission for notifcation 
    if #available(iOS 8, *){ 
     let mySettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: categories as? Set<UIUserNotificationCategory>) 
     UIApplication.sharedApplication().registerUserNotificationSettings(mySettings) 


     UIApplication.sharedApplication().cancelAllLocalNotifications() 

    } 

    return true 
    } 


func increaseScore(){ 


    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) 
    let context: NSManagedObjectContext = appDel.managedObjectContext 

    let proxy = NSEntityDescription.insertNewObjectForEntityForName("Proxy", inManagedObjectContext: context) as NSManagedObject 
    proxy.setValue(1, forKey: "present") 
    proxy.setValue(NSDate(), forKey: "date") 



    do { 
     try context.save() 
    } catch { 
     print("error") 
    } 
    print(proxy) 
    print("Object Saved") 
    } 




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

     if(identifier == "FIRST_ACTION"){ 
      NSNotificationCenter.defaultCenter().postNotificationName("actionOnePressed", object: nil) 
     } else    if(identifier == "SECOND_ACTION"){ 
      NSNotificationCenter.defaultCenter().postNotificationName("actionTwoPressed", object: nil) 
     } 

     completionHandler() 
} 

//ViewController.Swift//

 // setting notfication action 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "increaseScore", name: "actionOnePressed", object: nil) 
    //scheduling notification 
    let dateComp:NSDateComponents = NSDateComponents() 
    dateComp.year = 2015; 
    dateComp.month = 11; 
    dateComp.day = 02; 
    dateComp.hour = 22; 
    dateComp.minute = 50; 
    dateComp.timeZone = NSTimeZone.systemTimeZone() 

    let calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! 
    let date:NSDate = calendar.dateFromComponents(dateComp)! 

    let notification:UILocalNotification = UILocalNotification() 
    notification.category = "FIRST_CATEGORY" 
    notification.alertBody = "hey been to college? " 
    notification.fireDate = date 
    notification.repeatInterval = NSCalendarUnit.Day 

    let dateNow = NSDate() 
    let noticalendar = NSCalendar.currentCalendar() 
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow) 

    if isalerViewShown == false && hour >= 15 { 

     UIApplication.sharedApplication().scheduleLocalNotification(notification) 
    }} 
+0

Какой метод код ViewController.swift существует в? –

+0

какой способ? @CharlesA. –

ответ

0

Чтобы обрабатывать локальные уведомления, когда ваше приложение не открыто, вы должны проверить словарь параметров запуска в application:didFinishLaunchingWithOptions:. Местное уведомление доставляется вам в этом словаре.

По the documentation for application:didReceiveLocalNotification::

Если пользователь выбирает, чтобы открыть приложение, когда происходит локальное оповещение, варианты запуска СЛОВАРЬ передаются приложению: willFinishLaunchingWithOptions: и применения: didFinishLaunchingWithOptions: методы содержит ключ UIApplicationLaunchOptionsLocalNotificationKey. Этот метод вызывается в какой-то момент после приложения вашего делегата: метод didFinishLaunchingWithOptions:.

Вот пример того, как можно было бы обрабатывать локальные уведомления в общем смысле:

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     let notificationSettings = UIUserNotificationSettings(forTypes: [.Sound, .Alert], categories: nil) 
     UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) 

     if let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { 
      let alertController = UIAlertController(title: "Notification", message: "A notification was received while the app was not running, and the user launched the app", preferredStyle: .Alert) 
      alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) 
     } 

     return true 
    } 

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { 
     let alertController = UIAlertController(title: "Notification", message: "A notification was received while the app was running", preferredStyle: .Alert) 
     alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
     window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) 
    } 

    var window: UIWindow? 
} 
+0

хорошо, поэтому коды, которые находятся в ViewController, я должен поместить их в приложение: didFinishLaunchingWithOptions: this? –

+1

Независимо от того, какое действие вы хотите предпринять в ответ на локальное уведомление, вам нужно сделать в 'application: didFinishLaunchingWithOptions:', если в словаре 'launchOptions' есть локальное уведомление. –

+0

okay @CharlesA спасибо, что помогаете мне и жаль, что я задаю глупые вопросы, но вы можете дать мне пример, потому что я не слишком хорошо знаком с этими значащими словами –

Смежные вопросы