Keywords: App Transport Security | iOS 9 | ATS Configuration | Info.plist | Network Connection Security
Abstract: This article provides a comprehensive analysis of connection failures caused by the App Transport Security (ATS) policy introduced in iOS 9 and Xcode 7, along with detailed solutions through Info.plist configuration. Includes complete code examples and step-by-step implementation guidelines to help developers understand ATS mechanisms and configure secure connections properly.
Problem Background and Symptom Analysis
With the release of iOS 9 and Xcode 7, Apple introduced the App Transport Security (ATS) policy, which mandates that all network connections must use HTTPS encrypted transmission. This change caused connection failures in many applications that previously relied on HTTP protocols.
In the specific case encountered by developers, when calling the following web service method:
- (void)ServiceCall:(NSString*)ServiceName :(NSString *)DataString
{
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
[sessionConfiguration setAllowsCellularAccess:YES];
[sessionConfiguration setHTTPAdditionalHeaders:@{ @"Accept" : @"application/json" }];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",ServiceURL]];
NSLog(@"URl %@%@",url,DataString);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:[NSString stringWithFormat:@"%@=%@", strSessName, strSessVal] forHTTPHeaderField:@"Cookie"];
request.HTTPBody = [DataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"Post";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error)
{
NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] delegate].window animated:YES];
});
return;
}
NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
for (NSHTTPCookie * cookie in cookies)
{
NSLog(@"%@=%@", cookie.name, cookie.value);
strSessName=cookie.name;
strSessVal=cookie.value;
}
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
}
The system returns the error message: "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection" with error code -1022. This error clearly indicates the root cause: the ATS policy requires secure connections.
In-depth Analysis of ATS Policy
App Transport Security is a security mechanism introduced by Apple in iOS 9 and OS X El Capitan, designed to enhance the security of application network communications. ATS requires by default:
- All network connections must use TLS 1.2 or higher
- Communication must use HTTPS protocol
- Certificates must meet forward secrecy requirements
- Use AES-128 or AES-256 encryption algorithms
The introduction of this policy reflects Apple's strong emphasis on user data security, but it also created compatibility issues for existing applications relying on HTTP services.
Solution Implementation
To address connection issues caused by ATS, the most direct solution is to configure ATS exceptions by modifying the project's Info.plist file. Here are the specific implementation methods:
Method 1: Completely Disable ATS (Not Recommended for Production)
Add the following configuration to Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
This configuration allows the application to load arbitrary HTTP content but significantly reduces the application's security level. Apple officially discourages using this configuration in production environments.
Method 2: Configure Exceptions for Specific Domains (Recommended Approach)
A more secure approach is to configure ATS exceptions for specific domains while maintaining security requirements for others:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
This configuration approach offers the following advantages:
- Relaxes security requirements only for specified domains
- Maintains ATS protection for other domains
- Aligns with Apple's security best practices
- Facilitates future migration to HTTPS
Detailed Configuration Steps
Complete workflow for configuring ATS exceptions in actual projects:
- Open the project in Xcode and locate the Info.plist file
- Right-click and select "Add Row", add
NSAppTransportSecuritykey with Dictionary type - Add
NSExceptionDomainssubkey toNSAppTransportSecuritydictionary, type Dictionary - Add domains that require exceptions as keys in
NSExceptionDomains, with Dictionary values - Set
NSExceptionAllowsInsecureHTTPLoadstoYESin the domain dictionary - Optionally set
NSIncludesSubdomainstoYESto include all subdomains - Clean and rebuild the project
Security Considerations and Best Practices
While ATS exception configurations can solve current compatibility issues, developers should recognize:
- Apple may further restrict ATS exception usage in future version review guidelines
- The long-term solution should be migrating services to HTTPS
- For applications with user-defined connections, consider using
NSAllowsArbitraryLoadsbut thoroughly evaluate security risks - Regularly check HTTPS support status of services and develop migration plans
Code Optimization Recommendations
While resolving ATS issues, consider optimizing the original network request code:
// Improved session configuration
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = @{
@"Accept": @"application/json",
@"User-Agent": [self userAgentString]
};
// Use shared session for better performance
NSURLSession *session = [NSURLSession sharedSession];
// Enhanced error handling
if (error) {
if (error.code == NSURLErrorAppTransportSecurityRequiresSecureConnection) {
NSLog(@"ATS blocked the connection, please check Info.plist configuration");
}
// Other error handling logic
}
Through the above configurations and optimizations, developers can maintain application functionality while gradually transitioning to more secure network communication standards.