2016-05-24 26 views
4

我有一個Android應用程序,它使用舊版Android的BroadcastReceiver和基於JobScheduler的Android 5.0+實現,當手機連接到充電器時自動啓動我的應用程序(即,它執行一個IntentService來處理一些文件)。iOS - Swift - 手機插入時的回撥

我希望能夠在iOS上(在Swift中)做同樣的事情。我在Google和這個網站上發現了很少的搜索,我想也許NSNotificationCenter與此有關,但我仍然不知道。

那麼,在iOS上有沒有相當於這個?

謝謝。

回答

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