【问题标题】:iOS - Swift - Callback when phone gets plugged iniOS - Swift - 插入电话时的回调
【发布时间】:2016-09-21 23:28:17
【问题描述】:

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

我希望能够在 iOS(在 Swift 中)上做同样的事情。我在谷歌和这个网站上搜索的很少,我认为可能 NSNotificationCenter 与此有​​关,但我仍然不知道。

那么,iOS 上是否有类似的功能?

谢谢。

【问题讨论】:

    标签: android ios swift broadcastreceiver nsnotificationcenter


    【解决方案1】:

    在 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.")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 2020-10-25
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      相关资源
      最近更新 更多