swifthttpsrequestssl-certificateconfidential

Disable HTTPS GET certificate check


My Class:

func getUsers() {
    guard let url = URL(string: "https://localhost:5001/Zona/User") else {return print("ERROR")}

    let urlRequest = URLRequest(url: url)

    let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if let error = error {
            print("Request error: ", error)
            return
        }

        guard let response = response as? HTTPURLResponse else { return }

        if response.statusCode == 200 {
            guard let data = data else { return }
            DispatchQueue.main.async {
                do {
                    let decodedUsers = try JSONDecoder().decode([User].self, from: data)
                    self.users = decodedUsers
                } catch let error {
                    print("Error decoding: ", error)
                }
            }
        }
    }

    dataTask.resume()
}

When connecting to a local server, it gives an error that it is impossible to check sll

Request error: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “localhost” which could put your confidential information at risk."


Solution

  • add this entry to info.plist

    <key>NSAppTransportSecurity</key>
        <dict>
            <key>NSExceptionDomains</key>
            <dict>
                <key>server.com</key>
                <dict>
                    <key>NSExceptionAllowsInsecureHTTPLoads</key>
                    <true/>
                    <key>NSExceptionRequiresForwardSecrecy</key>
                    <false/>
                    <key>NSIncludesSubdomains</key>
                    <true/>
                </dict>
            </dict>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
            <key>NSAllowsLocalNetworking</key>
            <true/>
        </dict>
    

    and use the HTTP insteasd of HTTPS in URL