0

I am getting numerous failed requests with Alamofire 5.3, where the response object itself is nil, or the error is "cannot parse response". I can see from the server logs that all of those requests are returning valid.

Here is my setup:

API manager class:

let config = Alamofire.Session.default.session.configuration
self.session = Alamofire.Session(configuration: config, interceptor: AccessTokenInterceptor())

AccessTokenInterceptor:

class AccessTokenInterceptor: RequestInterceptor {
        func adapt(_ urlRequest: URLRequest, for session: Alamofire.Session, completion: @escaping (AdapterResult<URLRequest>) -> Void) {
            var adaptedRequest = urlRequest
            adaptedRequest.setValue("application/json", forHTTPHeaderField: "Accept")
            adaptedRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

            if let token = SettingsManager.shared.userToken {
                adaptedRequest.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
            }
            completion(.success(adaptedRequest))
        }
    }

This interceptor inserts my auth token from SettingsManager

I am also using the standard router for URLRequestConvertible where encoding is done by JSON serialization (dictionary) or Codable protocol (objects)

case .login(let body):
   request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
case .register(let object):
   request.httpBody = try JSONEncoder().encode(object)

What is strange is that I don't think I'm doing anything different from the many other times I've used Alamofire and now the first request I make fails but the following one succeeds. If I remove the interceptor, there is no change.

If I inspect the outgoing headers or body content, it all seems normal, but the response from Alamofire is nil.

UPDATE: By using OS_ACTIVITY_MODE and iOS 13 I was able to see that it was complaining about the request headers and protocol. The server is on Elastic Beanstalk so I've been trying to mess with the SSL policy but still the first request fails every time.

MechEngineer
  • 1,399
  • 3
  • 16
  • 27

1 Answers1

0

This turned into quite the rabbit hole, so in the interest of community improvement, here is what I found.

After searching through the activity log errors, I noticed that iOS was complaining about an invalid header type -- upgrade. Searching for that value I found this question about removing the header. I learned that Apache acts as a proxy on Elastic Beanstalk but there is a mix up for HTTP/2 headers in the request, and iOS does not like that.

To get away from the header value, I ended up switching to Nginx proxy. Since my application uses Laravel, I then needed to deal with correcting the pretty URLs. To do that I found this answer. Now my web and mobile application both seem to be getting along nicely.

MechEngineer
  • 1,399
  • 3
  • 16
  • 27