如何在 ios 应用中有条件地推送本地通知?

How to conditionally push local notification in ios app?

我正在开发一个 ios 应用程序,该应用程序将在应用程序发送到后台后发送通知。我只希望当用户在 MainviewController.swift 中将值设置为 true 时通知起作用。所以我有这样的东西:

 func setDelegateToTrue () {
      Appdelegate().setToStart()
 }

 func setDelegateToFalse () {
      Appdelegate().setToEnd()
 }

在我的 Appdelegate.swift 中,我有这样的东西:

 var started = false

 func applicationDidEnterBackground(application: UIApplication) {
      if(started) {
      let notification: UILocalNotification = UILocalNotification()
      notification.category = "FIRST_CATEGORY"
      notification.alertBody = "do not forget your app"
      notification.repeatInterval = NSCalendarUnit.Day
      notification.timeZone = NSTimeZone.defaultTimeZone()
      UIApplication.sharedApplication().scheduleLocalNotification(notification)
      started = false
     }
 }

 func setToStart() {
      started = true
 }

 func setToEnd() {
      started = false
 }

通知在没有 if 语句时工作正常,但是,当我有 if 语句并在 viewdidload 中调用 setDelegateToTrue() 时,它停止工作。似乎开始的布尔值在调用 setToStart() 后发生了变化,但实际上我可以从 setToStart() 中打印出一些东西。谁能帮帮我?

对于此行为,您可以使用 NSUserDefault: 将 Main ViewController 中的值设置为:

 NSUserDefaults.standardUserDefaults().setBool(true, forKey: "shouldSendNotification")

并在app delegate的applicationDidEnterBackground中访问这个用户默认如下:

func applicationDidEnterBackground(application: UIApplication) {
    let  shouldSendNotification = NSUserDefaults.standardUserDefaults().boolForKey("shouldSendNotification")
    if shouldSendNotification {
        let notification: UILocalNotification = UILocalNotification()
        notification.category = "FIRST_CATEGORY"
        notification.alertBody = "do not forget your app"
        notification.repeatInterval = NSCalendarUnit.Day
        notification.timeZone = NSTimeZone.defaultTimeZone()
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
         NSUserDefaults.standardUserDefaults().setBool(false, forKey: "shouldSendNotification")
    }
}

您的问题是您在 运行 AppDelegate().setToStart() 时创建了 AppDelegate 的新实例。因此,当它稍后调用的应用程序委托时,它的标志仍然设置为 false,因为您在不同的实例上设置了标志(立即被销毁)。

要执行您当前正在尝试的操作,您需要从 UIApplicationsharedApplication)获取 delegate 并在其上设置标志。

在使用 OO 语言与视图控制器等进行通信时请牢记这一点,因为您始终需要获取要与之交谈的实例,而不是创建一个新实例。

您需要做的是

 func setDelegateToTrue () {
  AppDelegate.sharedAppDelegate().setToStart()
 }

 func setDelegateToFalse () {
  AppDelegate.sharedAppDelegate().setToEnd()
 }