你能获得Apple Watch的大概电池百分比吗?

时间:2015-03-25 12:39:36

标签: ios swift ios8 apple-watch

Apple Watch是否有可以访问其大致电池寿命的对象或功能?

4 个答案:

答案 0 :(得分:3)

这是可能的,但仅限于WatchOS 4的发布.UIDevice仅适用于iOS设备,因此它与此问题完全无关。它的对应部分是WatchOS中的WKInterfaceDevice。

正确的解决方案是:

  

OBJECTIVE-C版

float *watchBatteryPercentage = [WKInterfaceDevice currentDevice].batteryLevel;

但你必须先允许它:

[WKInterfaceDevice currentDevice].batteryMonitoringEnabled = YES;
  

SWIFT 4.2版本:

var watchBatteryPercentage:Int {
    return Int(roundf(WKInterfaceDevice.current().batteryLevel * 100))
}

要使其可用,您必须使用:

WKInterfaceDevice.current().isBatteryMonitoringEnabled = true

答案 1 :(得分:2)

根据Sean的说法,您无法在当前的WatchKit版本中获得Apple Watch电池级别,以下代码只返回iPhone电池级别:

夫特:

var x = UIDevice.currentDevice().batteryLevel

目标-C:

int x = [UIDevice currentDevice].batteryLevel;

这是在App Store上的Battery Adviser Apple Watch应用程序(Applestan)中使用的代码。

答案 2 :(得分:1)

Swift(WatchKit 4.x)版本。请注意,您必须设置isBatteryMonitoringEnabled = true,否则您将无法获得有效结果。在我的情况下,我不关心后续通知,所以我立即回到假。另请注意,当前模拟器不会模拟batteryLevel / batteryState。

    let curDevice = WKInterfaceDevice.current()
    curDevice.isBatteryMonitoringEnabled = true // Enable just long enough for data
    let chargeLevel = curDevice.batteryLevel
    let chargeState = curDevice.batteryState
    curDevice.isBatteryMonitoringEnabled = false

答案 3 :(得分:-3)

这应该有效:UIDevice.currentDevice().batteryLevel这将返回一个Float

相关问题