首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS UIDevice Swift

iOS UIDevice Swift
EN

Stack Overflow用户
提问于 2014-12-16 01:48:50
回答 1查看 5.9K关注 0票数 2

我正在做一个项目,我想看看近邻探测器是否工作,以及batteryState是什么。这是我的密码-

代码语言:javascript
复制
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)
    }
}

我的问题是,我似乎得到了(Enum值),因为我的BatteryState和ProximityState的输出总是错误的(即使是被搁置和屏幕是黑色的)。另外,如何比较BatteryState (它不是字符串)?这可能有点下流,但我只是在学斯威夫特.

EN

回答 1

Stack Overflow用户

发布于 2014-12-16 01:54:54

您应该以小写字母开始命名您的函数。你应该这样做:

代码语言:javascript
复制
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属性的值仍然为假,则无法使用邻近监视。

代码语言:javascript
复制
var proximityState: Bool {
    UIDevice.currentDevice().proximityMonitoringEnabled = true

    return UIDevice.currentDevice().proximityMonitoringEnabled ? UIDevice.currentDevice().proximityState : false
}

用法:

代码语言:javascript
复制
let myBatteryStateDescription = batteryState

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

if proximityState {
    // do this
} else {
    // do that
} 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27496266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档