2016-08-16 76 views
2

我正在做一個HTTP GET請求,隨機它將返回一個空數組,每個請求返回一個200 OK狀態碼,是否得到正確的響應。URLSession從HTTP GET請求返回空陣列

我檢查了網址的鉻,他們是正確的,我一直無法在iOS以外重現此錯誤。我目前正在做的是遞歸調用這個方法直到它讓我回到正確的響應。

有時它會給我一個填充數組的正確響應,有時它不會給我一個空數組,即使對於相同的調用。

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() 


} 

傳入parseStopEstimateJson()的數據有時是兩個字節。 []

有誰知道我的電話爲什麼會導致不一致的響應?

回答

0

如果數據被以任何方式截斷(這是唯一可能在客戶端出錯),它將無法解析,你會得到零或異常(不知道哪個)。

因爲你得到一個空數組,這意味着服務器正在發送一個空數組,而問題在於服務器端代碼,而不是客戶端代碼。

N.B. 「GET」應該是全部大寫。這也是默認設置,所以你根本不需要設置它。但這可能與失敗無關。