2016-09-17 95 views
0

免責聲明:忽略使用此產品的生產應用程序可能會或可能不會通過審覈的事實。我只是想讓這個概念起作用。下面是我試圖執行的代碼,我試圖做的所有代碼(現在)都是初始化四個常量,並且在第三個常量上有困難。IBAction的關鍵值編碼符合性錯誤

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的觸發)只發生它有四行代碼。

作爲參考,我試圖實現什麼this post在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); 

沒有編譯時錯誤或警告,和I」如何繼續下去。謝謝。

回答

1

工作的Xcode 8個β,夫特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 
+0

我喜歡這個想法,這是一個更好的方法。我得到的錯誤是編譯時,在第二行,「類型'[String:AnyObject]的值沒有成員'值'」 – WillB

+0

您正在使用Swift 3.0嗎? –

+0

是的,我更新到Xcode 8,並在大約一小時前在Swift 3中啓動了此項目。 – WillB

相關問題