BCMET25
BCMET25

Reputation: 21

iOS UIDevice Swift

I'm working on a project and I want to see whether or not the proximity detector is working and what the batteryState is. Here is my code-

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)
    }
}

My problem is I just seem to get (Enum value) as my output for BatteryState and the ProximityState is always false (even when held up and screen is black). Also, how can I compare the BatteryState (it is not a string? This is probably noobish but I'm just learning Swift...

Upvotes: 2

Views: 6308

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236350

You should name your functions starting with a lowercase letter. You should do as follow:

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
}

Enable proximity monitoring only when your application needs to be notified of changes to the proximity state. Otherwise, disable proximity monitoring. The default value is false.

Not all iOS devices have proximity sensors. To determine if proximity monitoring is available, attempt to enable it. If the value of the proximityMonitoringEnabled property remains false, proximity monitoring is not available.

var proximityState: Bool {
    UIDevice.currentDevice().proximityMonitoringEnabled = true

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

usage:

let myBatteryStateDescription = batteryState

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

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

Upvotes: 1

Related Questions