Clip
Clip

Reputation: 3078

URLSession return empty array from HTTP GET request

I am making an HTTP GET request and randomly it will return an empty array, each request returns a status code of 200 OK, whether I get the correct response or not.

I have checked the URL's in chrome and they are correct and I have not been able to reproduce this error outside of iOS. What I am currently doing is recursively calling this method until it gives me back the correct response.

Sometimes it gives me the correct response of a populated array, sometimes it doesn't and gives me an empty array, even for the same call.

func getStopEstimation(routeId: String?, stopId: String?, completion: (result: String) -> Void) {

    let components: NSURLComponents = NSURLComponents(string: baseUrl + "GetMapStopEstimates")!

    var queryItems: [URLQueryItem] = []

    let apiKeyQueryItem: URLQueryItem = URLQueryItem(name: "apikey", value: apiKey)
    queryItems.append(apiKeyQueryItem)

    if routeId != nil {
        let routeIdQueryItem: URLQueryItem = URLQueryItem(name: "routeID", value: routeId)
        queryItems.append(routeIdQueryItem)
    }

    if stopId != nil {
        let stopIdQueryItem: URLQueryItem = URLQueryItem(name: "routeStopID", value: stopId)
        queryItems.append(stopIdQueryItem)
    }

    components.queryItems = queryItems

    let url: URL = components.url!

    var request: URLRequest = URLRequest(url: url)
    request.httpMethod = "Get"

    let session: URLSession = URLSession.shared

    session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: NSError?) in

    if ((error) != nil) {
        completion(result: "No vehciles on route")
    }

    completion(result: self.parseStopEstimateJson(data: data!, routeId: routeId!, stopId: stopId!))

    }.resume()


}

The data that gets passed into parseStopEstimateJson() sometimes is two bytes. []

Does anyone know why my calls are resulting in inconsistent responses?

Upvotes: 2

Views: 783

Answers (1)

dgatwood
dgatwood

Reputation: 10407

If the data were truncated in any way (which is the only thing that could go wrong on the client side), it would fail to parse and you'd get either nil or an exception (not sure which).

Because you're getting an empty array, that means the server is sending an empty array, and the problem is in the server-side code, not the client-side code.

N.B. "GET" should be all-caps. It is also the default, so you don't need to set it at all. But that's likely unrelated to the failure.

Upvotes: 1

Related Questions