ios - 处理程序不接收 batteryState 通知

标签 ios swift

我的 batteryStateDidChange 处理程序从未被调用(在模拟器或 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")
        }
    }
}

最佳答案

下划线后必须有空格

@objc func batteryStateDidChange(_ notification: Notification)

选择器就是

#selector(batteryStateDidChange)

关于ios - 处理程序不接收 batteryState 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47471972/

相关文章:

ios - 如何连接(GET请求)ios应用程序到django rest框架

struct - 结构体 Swift 中的变异相同的函数名

ios - xcodebuild:错误:未知的构建操作

ios - 是否可以枚举 NSDictionary 键来设置数据模型成员值?

ios - 已安装字体列表

iphone - UILocalNotification 不会触发

ios - 推送客户端错误 : Invalid Signature

ios - 无法导入 NYXImagesKit 库

ios - 用于将文件下载到 iOS 的 Cordova 文件传输插件

ios - 64 位 RGBA UIImage? 64 位的 CGBitmapInfo