其他分享
首页 > 其他分享> > android – iOS – Swift – 电话插入时回拨

android – iOS – Swift – 电话插入时回拨

作者:互联网

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

我希望能够在iOS上(在Swift中)做同样的事情.我发现很少在谷歌和这个网站上搜索,我想也许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.")
    }
}

标签:android,ios,swift,nsnotificationcenter,broadcastreceiver
来源: https://codeday.me/bug/20190706/1395311.html