|
| 1 | +import ExpoModulesCore |
| 2 | +import UIKit |
| 3 | + |
| 4 | +/// What the system says about the app's background refresh, which runs the background sync. |
| 5 | +enum BackgroundRefreshState: String { |
| 6 | + /// It runs. |
| 7 | + case on |
| 8 | + /// Turned off in Settings, for learnX or for every app. |
| 9 | + case off |
| 10 | + /// Paused while Low Power Mode is on. |
| 11 | + case lowPower |
| 12 | + /// Not allowed on this device (Screen Time or device management); the user may not be able to change it. |
| 13 | + case managed |
| 14 | +} |
| 15 | + |
| 16 | +/// What the state is read from; tests use a fake. |
| 17 | +@MainActor |
| 18 | +protocol BackgroundRefreshSystem { |
| 19 | + var refreshStatus: UIBackgroundRefreshStatus { get } |
| 20 | + var isLowPowerModeEnabled: Bool { get } |
| 21 | + var isMacCatalystApp: Bool { get } |
| 22 | +} |
| 23 | + |
| 24 | +@MainActor |
| 25 | +struct DeviceBackgroundRefresh: BackgroundRefreshSystem { |
| 26 | + var refreshStatus: UIBackgroundRefreshStatus { UIApplication.shared.backgroundRefreshStatus } |
| 27 | + var isLowPowerModeEnabled: Bool { ProcessInfo.processInfo.isLowPowerModeEnabled } |
| 28 | + var isMacCatalystApp: Bool { ProcessInfo.processInfo.isMacCatalystApp } |
| 29 | +} |
| 30 | + |
| 31 | +/// Says whether iOS lets the background sync run, so Settings can say why notifications of new content don't come. |
| 32 | +public final class BackgroundRefreshModule: Module { |
| 33 | + public func definition() -> ModuleDefinition { |
| 34 | + Name("BackgroundRefresh") |
| 35 | + |
| 36 | + AsyncFunction("getState") { () -> String in |
| 37 | + MainActor.assumeIsolated { |
| 38 | + Self.state(of: DeviceBackgroundRefresh()).rawValue |
| 39 | + } |
| 40 | + }.runOnQueue(.main) |
| 41 | + } |
| 42 | + |
| 43 | + @MainActor |
| 44 | + static func state(of system: BackgroundRefreshSystem) -> BackgroundRefreshState { |
| 45 | + // The Mac has no such setting, and runs the task while the app is open. |
| 46 | + if system.isMacCatalystApp { |
| 47 | + return .on |
| 48 | + } |
| 49 | + switch system.refreshStatus { |
| 50 | + case .available: |
| 51 | + return .on |
| 52 | + case .restricted: |
| 53 | + return .managed |
| 54 | + default: |
| 55 | + // Low Power Mode turns it off for every app until it ends, which isn't the setting to change. |
| 56 | + return system.isLowPowerModeEnabled ? .lowPower : .off |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments