处理程序未收到batteryState通知

时间:2017-11-24 11:07:06

标签: ios swift

我的batteryStateDidChange处理程序永远不会被调用(在Simulator或iPhone上)。我在这个网站上找到了几个例子(通常是旧的),我已经浏览了Apple文档。我也得到了pid错误:“由于系统完整性保护而无法附加到进程”,但我不确定这是否是原因。虽然自1970年代以来我一直在编程,但我以前从未使用过Swift或Xcode。我正在使用Swift 4和Xcode 9.1。帮助将不胜感激。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //Tell UIDevice that we want battery notifications
            UIDevice.current.isBatteryMonitoringEnabled = true

        // Register to listen for notifications
        NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange(_notification:)), name: Notification.Name.UIDeviceBatteryStateDidChange, object: nil)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    var batteryState: UIDeviceBatteryState {
        return UIDevice.current.batteryState
    }

    // Handle the batteryStateDidChange notification  <---- This never gets called
    @objc func batteryStateDidChange(_notification: Notification) {
        switch batteryState {
        case .unplugged, .unknown:
            print("not charging")
        case .charging, .full:
            print("charging or full")
        }
    }
}

2 个答案:

答案 0 :(得分:2)

下划线后面必须有空格字符

@objc func batteryStateDidChange(_ notification: Notification)

,选择器只是

#selector(batteryStateDidChange)

答案 1 :(得分:0)

代码看起来很好。只有当电池状态发生变化时才会调用batteryStateDidChange(拔掉充电或充电至完全充电)。

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