I'm trying to convert the following code into Swift 3. Its purpose is to print the cellular signal strength to the console. The StackOverflow post this came from can be found here.
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);
And, after my own attempts (swift is new to me), some online converters, and Xcode's automatic conversion from Swift 2.2 to 3, i'm stuck with two issues. Here is the current problematic code:
let app = UIApplication.shared
let subviews: NSArray = (((app.value(forKey: "statusBar"))! as AnyObject).value(forKey: "foregroundView"))!.subviews
var dataNetworkItemView: NSString?
for subview in subviews {
if (subview as AnyObject).isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
dataNetworkItemView = subview as? String as NSString?
break
}
}
let signalStrength = Int(((dataNetworkItemView!.value(forKey: "signalStrengthRaw") as! String) as NSString ?? "0").intValue)
print("signal \(signalStrength)")
The second line (let subviews: ...) throws the error:
'(AnyObject)' is not a subtype of 'NSObject'
and the second to last line (let signalStrength = ...) throws the following warning:
Left side of nil coalescing operator '??' has non-optional type 'NSString' so the right side is never used
The second issue makes more sense to me than the first, but how can I go about fixing the actual error? I'm not intending to be spoon-fed code but rather am trying to figure out why the error exists and what would satisfy the error and produce the desired results. Thanks :)