ma11hew28
ma11hew28

Reputation: 126397

Disable App Transport Security for Simulator only

How can I disable App Transport Security only when I run my app on the simulator (while still keeping it enabled when I run my app on my device, even in Debug mode)? Is there a way to disable it with Swift code instead of by modifying the Info.plist file?

I'm asking because I've configured things (via the code snippet below) so that the simulator connects (over HTTP) to a development server running on localhost and the device connects (over HTTPS) to the production server running in the cloud.

#if arch(x86_64) || arch(i386) // simulator
let apiBaseURLString = "http://localhost:3000"
#else                          // device
let apiBaseURLString = "https://api.example.com"
#endif

Ideally, I'd like keep App Transport Security enabled on the simulator and have the simulator connect over HTTPS to the development server running on localhost. I had that working, but I just updated Xcode, and it broke.

Upvotes: 3

Views: 2099

Answers (2)

wottle
wottle

Reputation: 13619

App Transport Security is configured at compile time by reading in the Info.plist. Changing it at runtime would actually have no effect on ATS enforcement, even if you could change the Info.plist at runtime (which you can't).

I can only think of two solutions:

  1. Simulator build config -You could create two versions of the Info.plist, one of which disables ATS altogether, the other is used for running on devices. You can then create a specific build config for running on the simulator. In your Build settings, choose the new Info-Simulator.plist which disables ATS. The downside of this is that you would need to change your build config before running on the simulator - it would not automatically use the correct build config for simulator vs. devices.

  2. Don't have different ATS settings for the simulator. Configure ATS to handle both the Simulator and physical devices. There are many options for ATS exceptions that should work for most scenarios. Need exceptions for local network connections? Look into NSAllowsLocalNetworking. Need more flexibility in a webview? Try NSAllowsArbitraryLoadsInWebContent.

Unfortunately, you can detect the simulator at runtime, but you can't change ATS behavior at runtime. You'll need to find another way, or re-evaluate if you really need a different config on simulators vs. devices.

Upvotes: 2

Abhishek Mitra
Abhishek Mitra

Reputation: 3395

I think this Code should work to access the .plist file, upon this code you can make changes what you need and put condition for that.

Bundle.main.object(forInfoDictionaryKey: key_name)

UPDATE

Here I'm Posting an Image please folow it:

enter image description here

Here you can get the value for:

NSAllowsArbitraryLoads = 1;

And through this you can put a condition according to your requirement.

Thanks

Upvotes: -1

Related Questions