iOS UIDevice Swift

iOS UIDevice Swift,ios,xcode,swift,Ios,Xcode,Swift,我正在做一个项目,我想看看接近探测器是否工作,电池状态是什么。这是我的密码- import Foundation import UIKit class DeviceMonitor { init() { UIDevice.currentDevice().batteryMonitoringEnabled = true UIDevice.currentDevice().proximityMonitoringEnabled = true //

我正在做一个项目,我想看看接近探测器是否工作,电池状态是什么。这是我的密码-

import Foundation
import UIKit

class DeviceMonitor {

    init() {
        UIDevice.currentDevice().batteryMonitoringEnabled = true
        UIDevice.currentDevice().proximityMonitoringEnabled = true

        //Loops for ease of checking
        var timer: Bool = true
        while (timer == true){
            sleep(2)
            BatteryState()
            ProximityState()
        }
    }

    func BatteryState() {
        var batterystate: UIDeviceBatteryState = UIDevice.currentDevice().batteryState
        println(batterystate)
    }

    func ProximityState() {
        var proximitystate: Bool = UIDevice.currentDevice().proximityState
        println(proximitystate)
    }
}

我的问题是,我似乎只是将(枚举值)作为我的BatteryState输出,而ProximityState始终为false(即使在被挂起且屏幕为黑色时)。另外,我如何比较BatteryState(它不是字符串?这可能是noobish,但我只是在学习Swift…

您应该以小写字母开头命名函数。您应该按照以下操作:

var batteryState: String {
    if UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Unplugged {
        return "Unplugged"
    }
    if UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Charging {
        return "Charging"
    }
    if UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Full {
        return "Full"
    }
    return "Unknown"
}

var batteryCharging: Bool {
    return UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Charging
}

var batteryFull: Bool {
    return UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Full
}

var unPlugged: Bool {
    return UIDevice.currentDevice().batteryState == UIDeviceBatteryState.Unplugged
}
仅当需要安装应用程序时才启用接近监视 通知接近状态的更改。否则,禁用 接近监视。默认值为false

并非所有iOS设备都有接近传感器。要确定是否接近 监视可用,请尝试启用它。如果 proximityMonitoringEnabled属性仍为false,邻近性 监控不可用

用法:

let myBatteryStateDescription = batteryState

let myProximityStateDescription = proximityState ? "True" : "False" 

if proximityState {
    // do this
} else {
    // do that
} 

非常感谢。由于某些原因,接近状态仍然保持为false tho…很抱歉,延迟回复我,您必须在检查之前启用它
let myBatteryStateDescription = batteryState

let myProximityStateDescription = proximityState ? "True" : "False" 

if proximityState {
    // do this
} else {
    // do that
}