Подтвердить что ты не робот

Обнаруживать, если устройство заряжается

Я не могу найти что-то определенное, используя мой любимый инструмент, однако я подумал, что я его вытащил...

Есть ли способ использовать iPhone SDK для приложения, чтобы определить, находится ли устройство в состоянии приема питания (зарядка, док-станция и т.д.)?

Я хотел бы иметь возможность автоматически отключать idleTimer, если устройство получает питание (в противном случае это заданная пользователем настройка).

4b9b3361

Ответ 1

Да, UIDevice может сказать вам следующее:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) {
    NSLog(@"Device is charging.");
}

Дополнительную информацию см. в UIDevice в документах и ​​других значениях батареиState.

Ответ 2

Вам лучше использовать:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

if ([[UIDevice currentDevice] batteryState] != UIDeviceBatteryStateUnplugged) {
      [UIApplication sharedApplication].idleTimerDisabled=YES;
    }

Это потому, что вы должны заботиться о себе два разных состояния - одно - зарядка аккумулятора, а другая - при полной зарядке.

Если вы действительно хотите получить полное представление об этом, вы должны зарегистрироваться для получения уведомлений о мониторинге батареи, чтобы вы могли снова включить таймер простоя, если пользователь отключил основную мощность и т.д.

Ответ 3

Swift 4

UIDevice.current.isBatteryMonitoringEnabled = true

if (UIDevice.current.batteryState != .unplugged) {
    print("Device is charging.")
}

Swift 3

UIDevice.currentDevice().batteryMonitoringEnabled = true;

if (UIDevice.currentDevice().batteryState != .Unplugged) {
    print("Device is charging.");
}

Ответ 4

Swift 3:

UIDevice.current.isBatteryMonitoringEnabled = true
let state = UIDevice.current.batteryState

if state == .charging || state == .full {
    print("Device plugged in.")
}

Ответ 5

Вы можете использовать центр уведомлений darwin и использовать имя события com. apple.springboard.fullycharged.

Таким образом вы получите уведомление о своем настраиваемом методе, вот фрагмент кода:

// Registering for a specific notification
NSString *notificationName = @"com.apple.springboard.fullycharged";
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                NULL,
                                yourCustomMethod,
                                (__bridge CFStringRef)notificationName,
                                NULL, 
                                CFNotificationSuspensionBehaviorDeliverImmediately);

// The custom method that will receive the notification
static void yourCustomMethod(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
  NSString *nameOfNotification = (__bridge NSString*)name;

  if([nameOfNotification isEqualToString:notificationName])
  {
    // Do whatever you want...
  }
} 

Ответ 6

Swift 4.2

Bool Value

    var batteryState: Bool {
        IDevice.current.isBatteryMonitoringEnabled = true
        let state = UIDevice.current.batteryState

        if state == .charging || state == .full {
            print("Device plugged in.")
            return true

        } else {
            return false
        }

    }

Ответ 7

func checkForCharging() {

UIDevice.current.isBatteryMonitoringEnabled = true

if UIDevice.current.batteryState != .unplugged {

print("Batery is charging")

} else if UIDevice.current.batteryState == .unplugged {

print("Check the cable")

}

Ответ 8

Если вы хотите проверить более одного места, чем-то вроде этого.

class Device {

    static let shared = Device()

    func checkIfOnCharcher() -> Bool {
        UIDevice.current.isBatteryMonitoringEnabled = true
        if (UIDevice.current.batteryState != .unplugged) {
            return true
        } else {
            return false
        }
    }
}

Использование:

if Device.shared.checkIfOnCharcher() == true { 
      //Some Code
} else { 
   // Some code
}