检测何时拔下并插入iPhone

时间:2016-12-13 20:10:11

标签: swift

我只是想编写一个简单的代码,用于检测iPhone何时拔下插头然后插入。但是是事件驱动的,而不是使用while循环。此代码可以正常工作,但不会检测手机是否已拔下,并且不会更新打印的文本。

修改 从长远来看,我只是希望手机在拔下iPhone时发出声音。 (抱歉留下最终目标。)我正在使用这个打印语句,所以我可以确保它正常工作。

func startCharger()
    {

        printscreen.text="Started charger protocol"

       UIDevice.current.isBatteryMonitoringEnabled=true

        if(UIDevice.current.batteryState == .unplugged)
        {
            printscreen.text="Battery is unplugged"
        }
        else
        {
            printscreen.text="Battery is plugged in"
        }
    }

2 个答案:

答案 0 :(得分:2)

快速实施Dule'码。 检查电源是否已连接。 将这些功能复制到您的课程中。 在viewDidLoad中调用isPowerConnected()

func isPowerConnected(){
    UIDevice.current.isBatteryMonitoringEnabled = true
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(batteryStateChanged),
        name: .UIDeviceBatteryStateDidChange,
        object: nil)
}

var chargingVar = "" //Empty Variable

func batteryStateChanged(){
    if (UIDevice.current.batteryState == .charging) {    //Here we check if the device is charging
        UIApplication.shared.isIdleTimerDisabled = true  //Here we disable the lock screen time out value
        self.chargingVar = "is charging. \u{1F603}" //Here we change the variable to "is charging" 
             chargingAlaer()    //If power is pluged in we send an Alert
      }else{
        self.chargingVar = "is not charging. \u{1F622} "  //Here we change the variable to "is not charging"  
             chargingAlaer()         //If power is not pluged we send an Alert
    }


}

func chargingAlaer(){
    let alertController = UIAlertController(title: "Charging Status",
                                            message: "Your device \(chargingVar)",
        preferredStyle: UIAlertControllerStyle.alert)
    let ok = UIAlertAction(title: "OK",
                           style: UIAlertActionStyle.default,
                           handler: {(action) -> Void in
    })
    alertController.addAction(ok)
    self.present(alertController, animated: true, completion: nil)
}

答案 1 :(得分:1)

您可以使用UIDeviceBatteryStateDidChange获取有关电池状态更改的通知,代码如下所示:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(batteryStateChanged),
    name: .UIDeviceBatteryStateDidChange,
    object: nil)

当然,您需要ViewController中的方法(或者您想要获取通知的位置)。在这个例子中:

func batteryStateChanged(){
    // Your logic
}