How to check if Mobile (Cellular) Data is enabled for your app
Another niche topic, that may be quite useful in certain situations.
Published: July 30, 2021 Sponsored I want a Press KitRecently I needed to check in app I am working on whether "Mobile Data" is enabled. And before we get to the solution, I want to be clear what I am talking about.
I am not talking about checking if cellular connection is available at the moment - that is the job for NWPathMonitor
. I needed to know, if in iOS Settings > Mobile Data, the switch is turned on for my app.
This was hard to find at first, but there is quite simple solution available thanks to the Core Telephony framework.
Using CTCellularData
Since iOS 9, there is class called CTCellularData
with quite a simple job. According to the docs:
An object indicating whether the app can access cellular data.
To use it, we can create instance and then check the restrictedState
property to see if our app can use mobile/cellular data or not.
let cellularData = CTCellularData()
if cellularData.restrictedState != .restricted {
// our app can use cellular data
}
Monitoring changes
There is also a handy option to get notified when this state changes. Meaning if user goes to Settings and either enables or disables Mobile Data access for our app.
You can use block named cellularDataRestrictionDidUpdateNotifier
. It will be called when there is state change to the Mobile Data access.
It will also be called the first time you assign to this property. Usage can look like this:
cellularData.cellularDataRestrictionDidUpdateNotifier = { newState in
let mobileDataAvailable = newState != .restricted
print(mobileDataAvailable)
}
And that is all.