2016-02-01 21 views
0

任何人都可以帮助我如何使用UISwitch的状态来打开/关闭在Appdelegate.swift中声明的本地通知?我如何使用UISwitch来关闭本地通知?

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) 
    } 
} 
+0

所以要禁用本地通知时完成'NSUserDefa ults.standardUserDefaults()。boolForKey(“switchState”)'是'false'? – marosoaie

+0

有没有标准的方式来关闭本地通知,你应该忽略它们'switchState'为'false'时。 – ishaq

+0

是的,当switchstate为false时,应禁用本地通知 –

回答

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 

    } 
+0

如何在我的AppDelegate(Matthew)中实现代码? :-) –

+0

您可以将目标切换到您的appDelegate对象的实例。但我会建议将通知传递给视图控制器,或者在视图控制器中重新声明它们。 'switchButton.addTarget(AppDelegate(),action:“presentNotification”,forControlEvents:UIControlEvents.ValueChanged)'然而,这种方法要求你的'presentNotification'写在App Delegate中。它还创建了一个不推荐的新AppDelegate对象。 – NSGangster