Feng's Notes

周海锋的个人博客

0%

iOS获取电量的方法

- (double)getCurrentBatteryLevel {
    UIApplication *app = [UIApplication sharedApplication];
    if (app.applicationState == UIApplicationStateActive || app.applicationState == UIApplicationStateInactive) {
        id statusBar;
        // 判断是否是iPhoneX, 兼容iOS12
        if ([[app valueForKeyPath:@"_statusBar"] isKindOfClass:NSClassFromString(@"UIStatusBar_Modern")]) {
            statusBar = (UIView *)[[app valueForKeyPath:@"_statusBar"] valueForKeyPath:@"_statusBar"];
            NSDictionary *items = [statusBar valueForKeyPath:@"_items"];
            
            if (items && [items isKindOfClass:[NSDictionary class]]) {
                for (id item in [items allValues]) {
                    NSLog(@"%@", NSStringFromClass([item class]));
                    if ([NSStringFromClass([item class]) caseInsensitiveCompare:@"_UIStatusBarBatteryItem"] == NSOrderedSame) {
                        UIView *batteryView = [item valueForKeyPath:@"_batteryView"];
                        double batteryLevel = [[batteryView valueForKeyPath:@"_chargePercent"] doubleValue];
                        if (batteryLevel > 0 && batteryLevel <= 1) {
                            return batteryLevel;
                        }
                    }
                }
            }
        } else {
            statusBar = (UIView *)[app valueForKeyPath:@"_statusBar"];
            for (id aview in [statusBar subviews]) {
                int batteryLevel = 0;
                for (id bview in [aview subviews]) {
                    if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame) {
                        Ivar ivar = class_getInstanceVariable([bview class],"_capacity");
                        if (ivar) {
                            batteryLevel = ((int (*)(id, Ivar))object_getIvar)(bview, ivar);
                            if (batteryLevel > 0 && batteryLevel <= 100) {
                                return batteryLevel / 100.0;
                            }
                        }
                    }
                }
            }
        }
    }
    return 0;
}