如何使用UISwitch来转换本地通知?

时间:2016-02-01 15:10:07

标签: ios swift uilocalnotification uiswitch

有人可以帮助我如何使用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)
  }
}

1 个答案:

答案 0 :(得分:0)

这应该可以使用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

    }