xyk blog

最近は iOS 開発の記事が多めです。

Swift で端末の低電力モード、Appのバックグラウンド更新の状態を取得する

検証環境:
Xcode 11.3
Swift 5.1.3

「低電力モード」になっているかを取得

if ProcessInfo.processInfo.isLowPowerModeEnabled {
    // Low Power Mode is enabled. Start reducing activity to conserve energy.
} else {
    // Low Power Mode is not enabled.
}

https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/LowPowerMode.html

「Appのバックグラウンド更新」の状態を取得

このステータスはアプリ毎に設定値を持つ。
以下画像はLINEアプリの例。

f:id:xyk:20200214145849j:plain
switch UIApplication.shared.backgroundRefreshStatus {
case .available:
    print("Refresh available")
case .denied:
    print("Refresh denied")
case .restricted:
    print("Refresh restricted")
}

UIBackgroundRefreshStatus の定義

@available(iOS 7.0, *)
public enum UIBackgroundRefreshStatus : Int {

    case restricted //< unavailable on this system due to device configuration; the user cannot enable the feature

    case denied //< explicitly disabled by the user for this application

    case available //< enabled for this application
}

https://developer.apple.com/documentation/uikit/uiapplication/1622994-backgroundrefreshstatus