iOS programatic Cellular Data Control

2019-09-11 03:08发布

问题:

Is there a way to programmatically access the "Cellular Data" options that are sometimes shown in apps?

Background

I have an application that uploads data files over the internet. I have given users the option of disabling this upload functionality when not connected to WiFi.

How

What I'm currently doing is I wrote a settings.bundle that allows the user to select an option called User Cellular Data in my code I am using a Reachability.swift file from (https://github.com/ashleymills/Reachability.swift) - which is a swift wrapper around the reachability iOS api - basically it can tell you if there is Wifi or cellular network access.

My code

In my code before doing uploads I check a NSUserDefaults value (as set by the settings.bundle)

let uploadOverCellular = NSUserDefaults.standardUserDefaults()
                         .boolForKey("allow_upload_over_cellular")

If this is true and I have either Wifi or Cellular internet I allow the upload to proceed. If this is not true and I have cellular internet I stop the upload.

So this is working nicely and then suddenly I was looking in the settings for my app and I noticed that I have both the System level Cellular Data option as well as my custom Use Cellular Data option. showing up

Question

Obviously this could cause some confusion for users - I wanted to know if there Is there API access to this system level Cellualr Data option - or some other way to control this setting programmatically - I suspect there is not but I'm hoping somebody can prove me wrong.

回答1:

I don't know if there's access to the global cellular data setting, but if you use NSURLSession APIs for downloading data, you can create an NSURLSessionConfiguration with allowsCellularAccess = false.