IBAction上的键值编码合规性错误

时间:2016-09-17 04:27:06

标签: ios swift swift3 nsunknownkeyexception anyobject

免责声明:忽略使用此功能的生产应用可能会或可能不会通过审核的事实。我只是想让这个概念起作用。这是我正在尝试执行的代码,我正在尝试做的(现在)是初始化四个常量,它在第三个上有困难。

let app = UIApplication.shared
let statusBar = app.value(forKey: "statusBar") as AnyObject
let foregroundView = statusBar.value(forKey: "foregroundView") as AnyObject
let subviews = Array(foregroundView.subviews)

给出错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_SwiftValue 0x170087850> valueForUndefinedKey:]: this class is not key value coding-compliant for the key foregroundView.'

请注意,与运行应用程序时发生的大多数其他键值合规性错误不同,我只会在执行包含四行代码的IBAction(由UIButton触发)时发生。

作为参考,我正在努力实现Objective-C中this post描述的内容。我是Swift的新手,但我认为我已正确翻译了它。

整个func在这里:

@IBAction func getSignal(_ sender: UIButton) {

    let app = UIApplication.shared
    let statusBar = app.value(forKey: "statusBar") as AnyObject
    let foregroundView = statusBar.value(forKey: "foregroundView") as AnyObject
    let subviews = Array(foregroundView.subviews)
    var dataNetworkItemView: UIView?
    for subview in subviews {
        if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
            dataNetworkItemView = subview
            break
        }
    }
    let signalStrength = (dataNetworkItemView?.value(forKey: "signalStrengthRaw") as? NSString)?.intValue
    print("signal \(signalStrength)")
}

我从原始代码块转换而来,这里:

    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"]     valueForKey:@"foregroundView"] subviews];
    NSString *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]])
        {
            dataNetworkItemView = subview;
            break;
        }
    }
    int signalStrength = [[dataNetworkItemView valueForKey:@"signalStrengthRaw"] intValue];
    NSLog(@"signal %d", signalStrength);

没有编译时错误或警告,我对如何继续而感到茫然。感谢。

1 个答案:

答案 0 :(得分:1)

使用Xcode 8 beta,Swift 3.0代码:

let app = UIApplication.shared
let statusBar = app().value(forKey: "statusBar")! as AnyObject
let foregroundView = statusBar.value(forKey: "foregroundView")! as AnyObject
let subviews = Array(foregroundView.subviews)
var dataNetworkItemView: UIView?
for subview in subviews {
    if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
        dataNetworkItemView = subview
        break
    }
}
let signalStrength = (dataNetworkItemView?.value(forKey: "signalStrengthRaw") as? NSString)?.intValue
print("signal \(signalStrength)")

OP正在使用Xcode 8 GM,因此只需更改app()app

let statusBar = app.value(forKey: "statusBar")! as AnyObject