1

This one's a weird one.

I have a little API server that does some stuff that I want my mobile app to talk to. It has DNS and SSL correct configured, I can reach it from my browser or postman no problem. Additionally I have set up a 301 redirect to HTTPS if anyone tries to approach it via HTTP.

I have a viewModel in swift thats calling out to this API with a pretty standard set up.

 func getEndpointData() {
        var urlComponents = URLComponents()
        urlComponents.scheme = "https"
        urlComponents.host = "mycoolApi.com"
        urlComponents.path = "/v1/endpoint/\(model.endpoint.param)"
        let url = urlComponents.url!
        
        let session = URLSession(configuration: .default)
        session.dataTaskPublisher(for: url)
            .tryMap(){ element -> Data in
                guard let httpResponse = element.response as? HTTPURLResponse,
                      httpResponse.statusCode == 200 else {
                    throw URLError(.badServerResponse)
                }
                return element.data
            }
            .decode(type: EndpointData.self, decoder: JSONDecoder())
            .receive(on: RunLoop.main)
            .sink(receiveCompletion: { print("recieved completion \($0)")},
                  receiveValue: { endpointData in
                    self.rawData = endpointData.myCoolProperty
                  })
            .store(in: &cancellables)
    }

Should be calling via HTTPS right? Wrong.

This is the error I get:

recieved completion failure(Foundation.URLError(_nsError: 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={NSLocalizedDescription=The resource could 
not be loaded because the App Transport Security policy requires the use of a secure 
connection., NSErrorFailingURLStringKey=http://mycoolApi.com/v1/endpoint/<Path_Param_ID>/, 
NSErrorFailingURLKey=http://mycoolApi.com/v1/endpoint/<Path_Param_ID>/, 
_NSURLErrorRelatedURLSessionTaskErrorKey=(

I feel like Im taking crazy pills.. Why is the simulator forcing something thats explicitly https to http?

snarik
  • 1,035
  • 2
  • 9
  • 15

1 Answers1

0

I am not sure if this is the right way but I recently faced this issue on my live app there are two possible solution one you add "App Transport Security Settings" & "Allow Arbitrary Loads" in your info.plist

check out the image for info.plist

Second thing which worked for me https://www.mycoolApi.com so you need "www" after https://

Omair
  • 7
  • 5