【问题标题】:How can i use UISwitch to turn of local notification?如何使用 UISwitch 关闭本地通知?
【发布时间】:2016-02-01 15:10:06
【问题描述】:

谁能帮助我如何使用 UISwitch 的状态来打开/关闭 Appdelegate.swift 中声明的本地通知?

Viewcontroller.swift:

@IBOutlet weak var switchButton: UISwitch!
var switchState = true
let switchKey = "switchState"

@IBAction func saveSwitchPressed(sender: AnyObject) {
  NSUserDefaults.standardUserDefaults().setBool(switchButton.on, forKey: "switchState")
}

override public func viewDidLoad() {
  super.viewDidLoad()
  switchButton.on =  NSUserDefaults.standardUserDefaults().boolForKey("switchState")
}

AppDelegate.swift

func handleRegionEvent(region: CLRegion) {
  // Show an alert if application is active
  if UIApplication.sharedApplication().applicationState == .Active {
    if let message = notefromRegionIdentifier(region.identifier) {
      if let viewController = window?.rootViewController {
        showSimpleAlertWithTitle(nil, message: message, viewController: viewController)
      }
    }
  } else {
     // Otherwise present a local notification
     let notification = UILocalNotification()
     notification.alertBody = notefromRegionIdentifier(region.identifier)
     notification.soundName = "Default";
     UIApplication.sharedApplication().presentLocalNotificationNow(notification)
  }
}

【问题讨论】:

  • 所以你想在NSUserDefaults.standardUserDefaults().boolForKey("switchState")false 时禁用本地通知?
  • 没有关闭本地通知的标准方法,当switchStatefalse 时,您应该忽略它们。
  • 是的,当 switchstate 为 false 时,应该禁用本地通知

标签: ios swift uilocalnotification uiswitch


【解决方案1】:

这应该可以使用 targetAction 来完成

   override public func viewDidLoad() {
        super.viewDidLoad()
        switchButton.on =  NSUserDefaults.standardUserDefaults().boolForKey("switchState")

        //Set button to observe target action
        switchButton.addTarget(self, action: "presentNotification", forControlEvents: UIControlEvents.ValueChanged) 
    }

    func presentNotification() {
        //Do notification stuff here

    }

【讨论】:

  • 如何在我的 AppDelegate (Matthew) 中实现代码? :-)
  • 您可以将目标切换到您的 appDelegate 对象的实例。但我建议要么将通知传递到您的视图控制器,要么在视图控制器中重新声明它们。 switchButton.addTarget(AppDelegate(), action: "presentNotification", forControlEvents: UIControlEvents.ValueChanged) 但是,这种方法要求您的 presentNotification 写在 App Delegate 中。它还会创建一个不推荐的新 AppDelegate 对象。
猜你喜欢
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多