The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

325,161

Solution 1

I have solved it with adding some key in info.plist. The steps I followed are:

  1. Opened my Project target's info.plist file

  2. Added a Key called NSAppTransportSecurity as a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image.

enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link: https://stackoverflow.com/a/32609970

EDIT: OR In source code of info.plist file we can add that:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>yourdomain.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
       </dict>
  </dict>

Solution 2

Be aware, using NSAllowsArbitraryLoads = true in the project's info.plist allows all connection to any server to be insecure. If you want to make sure only a specific domain is accessible through an insecure connection, try this:

enter image description here

Or, as source code:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>domain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Clean & Build project after editing.

Solution 3

Transport security is provided in iOS 9.0 or later, and in OS X v10.11 and later.

So by default only https calls only allowed in apps. To turn off App Transport Security add following lines in info.plist file...

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

For more info:
https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

Solution 4

For iOS 10.x and Swift 3.x [below versions are also supported] just add the following lines in 'info.plist'

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Solution 5

In Swift 4 You can use

->Go Info.plist

-> Click plus of Information properties list

->Add App Transport Security Settings as dictionary

-> Click Plus icon App Transport Security Settings

-> Add Allow Arbitrary Loads set YES

Bellow image look like

enter image description here

Share:
325,161
Manab Kumar Mal
Author by

Manab Kumar Mal

An iOS Application Developer (SWIFT, Objective C), want to achieve height of success in my career by contributing to the field of Information Technology with my Knowledge in iOS(Swift, Objective C), skills, patience &amp; Team spirit. I wish to see myself with enhanced responsibilities contributing to the success of the firm. I worked on- Follow MVP, singleton, delegation &amp; extension, Facade, Observer, memento etc design patterns. Notifications (Remote and Local). Core Location and Mapkit frameworks. In app purchase. MPL(Mobile payment libs) like Paypal, Stripe etc Core animations, UIView animations, quartz core frameworks. JSON and XML parser. Social network framework integrations like Facebook, Twitter, LinkedIn etc. Collection view, Split view ipad, Table view - with customize cell, picker view, etc. Core data, SQLite, Keychain Access, User defaults, Plist etc as persistence storage iAD framework GCD and Queue for thread handling Autolayout and manual constraint set up Localization SMS functionality, email functionality, Core Telephony framework. Rest APIs Google Firebase and Analytics and others Languages: Swift, Objective-C

Updated on June 03, 2021

Comments

  • Manab Kumar Mal
    Manab Kumar Mal about 3 years

    I am facing the Problem when I have updated my Xcode to 7.0 or iOS 9.0. Somehow it started giving me the Titled error

    "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection"

    Webservice 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);
        // Configure the Request
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setValue:[NSString stringWithFormat:@"%@=%@", strSessName, strSessVal] forHTTPHeaderField:@"Cookie"];
        request.HTTPBody = [DataString dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPMethod = @"Post";
    
        // post the request and handle response
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                              {
                                                  // Handle the Response
                                                  if(error)
                                                  {
                                                      NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
    
                                                      // Update the View
                                                      dispatch_async(dispatch_get_main_queue(), ^{
    
                                                          // Hide the Loader
                                                          [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 service is Running fine for Xcode earlier versions and iOS previous versions But when I have updated to Xcode 7.0 that is on iOS 9.0, it started to give me the Problem like following when I am calling the above web service method. The Logged Error which I am getting is:

    Connection failed: Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x7fada0f31880 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=MyServiceURL, NSErrorFailingURLKey=MyServiceURL, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

    I have tried Following Questions and answers but did not get any result there, is there any advance idea how I can remove that service call error?

    1. The resource could not be loaded is ios9
    2. App Transport Security Xcode 7 beta 6
    3. https://stackoverflow.com/a/32609970
  • Tony B
    Tony B almost 9 years
    Unless, of course, you cannot use HTTPS because Apple does not like self-signed certifcates. Do you not have that problem?
  • pierre23
    pierre23 almost 9 years
    In my case, it works perfectly since I changed to HTTPS
  • Tony B
    Tony B almost 9 years
    but do you use a self-signed or CA signed certificate? Just curious. Sort of a separate issue, of course, but figured I would ask.
  • pierre23
    pierre23 almost 9 years
    I didn't work on the server side, I don't know to be honest :(
  • Raptor
    Raptor over 8 years
    Setting up HTTPS connection on some server environments (shared hosting) might be difficult.
  • Cherry_thia
    Cherry_thia over 8 years
    I cannot send use mail after i added this. it gives me an error - MailCompositionService quit unexpectedly.
  • orafaelreis
    orafaelreis over 8 years
    It's not work at first. You need to add the keys inside Project > Target too
  • LargeGlasses
    LargeGlasses over 8 years
  • neeta
    neeta over 8 years
    thanks for your answer just NSAllowArbitaryLoads didn't work for me adding NSExceptionAllowsInsecureHTTPLoads did the trick
  • Mihir Oza
    Mihir Oza over 8 years
    Thanks for saving my day. Is this error come because of IOS 9??
  • Sandy D.
    Sandy D. about 8 years
    I also added these two keys: <!--Include to allow HTTP requests--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <!--Include to specify minimum TLS version--> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.1</string> It made it load a LOT quicker too.
  • Dominic K
    Dominic K about 8 years
    @MihirOza: Yep, transport security is a new feature of iOS 9.
  • Josh
    Josh about 8 years
    Works like charm. It is not an error, it is just extra security in iOS.
  • NSGangster
    NSGangster almost 8 years
    If I get this error in a different target i. e. a share extension target. Do i add it to that target's info.plist or the entire projects?
  • DawnSong
    DawnSong over 7 years
    If you have no exception domains, just remove any key under NSExceptionDomains. Or else it will be an exception to NSAllowArbitraryLoads, then you must use https to visit this exception
  • ArielSD
    ArielSD over 7 years
    Note: I'm using XCode 8 now: If you're doing this manually, make sure to right click on the domain > Value Type > Dictionary to add "..AllowsInsecure..." and "...IncludesSubdomains"
  • Swapna Lekshmanan
    Swapna Lekshmanan about 7 years
    For Xcode 8.3 / Swift 3 it is App Transport Security Settings and Allow Arbitrary Loads respectively
  • Jazzmine
    Jazzmine almost 7 years
    For 10.x and Swift 3.x, I had seen elsewhere that the keys were actually AppTransportSecurity and AllowsArbitraryLoads but those were wrong. the NS prefix is still needed for these keys, even for Swift 3.x. The error went away when I relied on the NS prefix for these keys.
  • Shefy Gur-ary
    Shefy Gur-ary over 6 years
    Just adding my 2 cents. If you tried it and it doesn't work. Make sure you do it on the right info.plist you can have more than 1 of these files.
  • mmdush
    mmdush over 5 years
    One old project had "ProjectName-Info.plist" file instead of "Info.plist", noticed only after while trying to create new info.plist file. Added to this file and worked great.
  • Nike Kov
    Nike Kov over 5 years
    You should NOT disable it! It's unsafe. Check ste.vn/2015/06/10/…
  • Shamsiddin Saidov
    Shamsiddin Saidov about 5 years
    Not working if I specify port number after domain.com. (domain.com:3001 for example)
  • Mrug
    Mrug over 4 years
    But, this is still not allowing me to make HTTP call to any domain. Is there any clue why is it happening?
  • jones
    jones over 4 years
    Thanks, this worked for me! I only edited the plist file before which didnt work. Im surprised how other people got it working that way
  • Teja Kumar Bethina
    Teja Kumar Bethina about 4 years
    Even its a HTTP URL, the URL shoulb be bverified or should have a vlid SSL certificate.
  • pAkY88
    pAkY88 about 4 years
    Thanks for this information. You saved me hours of troubleshooting.
  • Shahid Ghafoor
    Shahid Ghafoor over 3 years
    I have tried above solution, http based apis are being called but I can not stream video. any idea how we can stream video that is http based?
  • M Hamayun zeb
    M Hamayun zeb over 2 years
    Working for me.....
  • yerlilbilgin
    yerlilbilgin about 2 years
    Don't tell or force people to use HTTPS, they might have some other requirements. That is not an answer at all.