iOS - Swift - phone 插入时的回调

iOS - Swift - Callback when phone gets plugged in

我有一个 Android 应用程序,它为 Android 的旧版本使用 BroadcastReceiver,并为 Android 5.0+ 使用基于 JobScheduler 的实现,当 phone 连接到充电器(即它执行一个 IntentService 来处理一些文件)。

我希望能够在 iOS(在 Swift 中)执行相同的操作。我在 Google 和这个网站上搜索很少,我想也许 NSNotificationCenter 与此有​​关,但我仍然不知道。

那么,iOS 上是否有与此等效的内容?

谢谢。

在 iOS 中,我们并不像在 Android 中那样始终拥有相同的设备级访问权限。我们的应用程序只有在未终止时才能收到电池状态等通知。

当您的应用程序处于前台状态时,请尝试使用以下代码来访问设备的电池状态。

// Begins battery state monitoring //
UIDevice.currentDevice().batteryMonitoringEnabled = true
// Check for battery's current status //
if (UIDevice.currentDevice().batteryState != .Unplugged) {
    print("Device is plugged in.")
}

您还可以 运行 以下代码在您的应用程序进入后台时在设定的时间检查设备的电池状态。 注意 - 执行以下操作很可能会导致您被 App Store 版本拒绝。

func applicationDidEnterBackground(application: UIApplication) {
    // Begins battery state monitoring //
    UIDevice.currentDevice().batteryMonitoringEnabled = true
    // Schedules NSTimer with intervals of 10 seconds //
    NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(batteryCheck), userInfo: nil, repeats: true)
}

func batteryCheck() {
    if (UIDevice.currentDevice().batteryState != .Unplugged) {
        print("Device is charging.")
    } else {
        print("Device is NOT charging.")
    }
}