ios - 杀死(完全关闭)应用程序后,UILocalNotification 操作不起作用

标签 ios swift uilocalnotification

我使用一个函数在我的应用程序上实现了 UILocalNotification,当应用程序在后台运行时它工作正常,但是当我完全关闭应用程序时,会出现通知,但与之关联的函数没有执行任何操作,如果有人知道的话我做错了什么或者如何正确地做而不是帮助我

//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)
    }}

最佳答案

要在应用未打开时处理本地通知,您必须检查 application:didFinishLaunchingWithOptions: 中的启动选项字典。本地通知将在该字典中传递给您。

根据the documentation for application:didReceiveLocalNotification: :

If the user chooses to open the app when a local notification occurs, the launch options dictionary passed to the application:willFinishLaunchingWithOptions: and application:didFinishLaunchingWithOptions: methods contains the UIApplicationLaunchOptionsLocalNotificationKey key. This method is called at some point after your delegate’s application:didFinishLaunchingWithOptions: method.

以下是一般意义上如何处理本地通知的示例:

@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?
}

关于ios - 杀死(完全关闭)应用程序后,UILocalNotification 操作不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185457/

相关文章:

ios - 为什么滑动以删除并拉动刷新会导致崩溃?

ios - 检测未使用的方法 iOS

ios - Objective-C 消息被发送到已释放的 'UIActivityIndicatorView' 对象

ios - 从另一个包含字符串的数组快速返回数组

swift - iOS 13 - 当 Search Active Push 到其他 VC 时,VC UITableView 在 Swift 4 的 NavigationBar 下

iOS App Distribution 作为私有(private)应用程序

android - 缩小 flutter 底部导航栏小部件之间的间隙

ios - 自定义 UILocalNotification 的警报

iphone - 本地通知“每天上午7:00”通知

ios - 使用 UILocalNotification 安排事件