我正在尝试从AppDelegate内的一个ViewController访问布尔值。但是当我这样做时,它会打印错误,但我希望它设置为true。
这是我的代码: 我在ViewWillAppear()
之外声明了这个变量 var mainIsON = Bool()
//...
@IBAction func mainSwitchState(_ sender: UISwitch) {
if mainSwitch.isOn{
mainIsON = true
}
}
然后我想在AppDelegate中检查它。 我声明一个像这样的对象来访问AppDelegate顶部的SettingsViewController:
let settings = SettingsViewController()
//...
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("received silent push notification")
if settings.mainIsON == true {
LocalPushManager.shared.sendLocalPushRepeating(in: 60, plant: 1)
}
// LocalPushManager.shared.sendLocalPushRepeating(in: <#T##TimeInterval#>, plant: )
completionHandler(UIBackgroundFetchResult.newData)
}
但是代码只是跳过了,当我运行调试器时,我得到的mainIsON是假的。我做错了什么?
答案 0 :(得分:1)
问题实际上在你的行
let settings = SettingsViewController() //in AppDelegate
当您编写此行时,它实际上会创建一个新的SettingView Controller实例
当控件到达
时创建一个新实例var mainIsON = Bool()
你的mainIsON bool再次被分配,它的默认值为False这就是你面对上述问题的原因
解决方案:使用结构
struct settingBool {
static var mainIsON:Bool=False /// Setting Default as False
}
现在在SettingViewController
中@IBAction func mainSwitchState(_ sender: UISwitch) {
if mainSwitch.isOn{
settingBool.mainIsON = true
}
}
和AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("received silent push notification")
if settingBool.mainIsON == true {
LocalPushManager.shared.sendLocalPushRepeating(in: 60, plant: 1)
}
// LocalPushManager.shared.sendLocalPushRepeating(in: <#T##TimeInterval#>, plant: )
completionHandler(UIBackgroundFetchResult.newData)
}
解决方案2 - 使用AppDelegate ItSelf:不首选 在App Delegate中自己创建一个Bool变量
var mainISOn : Bool = false
并且只需像
那样访问它let appDel = UIApplication.shared.delegate as! AppDelegate
appDel.mainISOn = false
支票将像
@IBAction func mainSwitchState(_ sender: UISwitch) {
if mainSwitch.isOn{
let appDel = UIApplication.shared.delegate as! AppDelegate
appDel.mainIsON = true
}
}
现在在AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("received silent push notification")
if self.mainIsON == true {
LocalPushManager.shared.sendLocalPushRepeating(in: 60, plant: 1)
}
// LocalPushManager.shared.sendLocalPushRepeating(in: <#T##TimeInterval#>, plant: )
completionHandler(UIBackgroundFetchResult.newData)
}