免责声明:忽略使用此功能的生产应用程序可能会或可能不会通过审核的事实。我只是想让这个概念发挥作用。这是我正在尝试执行的代码,我正在尝试做的所有事情(目前)是初始化四个常量,第三个常量有困难。
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 中描述的内容。我是 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);
没有编译时错误或警告,我不知道如何继续。谢谢。