When I use URLSession in a Swift iOS app to fetch data from my server I get a 200 response, but the response body is incomplete (it appears to be truncated, leading to an invalid json). When I make the same request on Postman it works as expected, returning the full response body, so the issue seems to be isolated to iOS.
I am not sure what steps to take next to debug the issue. Any help or tips would be appreciated.
class NetworkManager{
static let shared = NetworkManager(baseUrl: "https://my-url.com");
let baseUrl: URL
let session: URLSession
var token: String?
private init(baseUrl: String) {
// TODO: Throw well defined error
self.baseUrl = URL(string: baseUrl)!
let configuration = URLSessionConfiguration.default
self.session = URLSession(configuration: configuration)
}
}
class Fetcher<T, G>: ObservableObject where T: Decodable, G: Codable {
@Published var data: T? = nil
@Published var isLoading: Bool = false
public var path: [String] { return [] }
func fetchData(body: G) async
throws {
Task { @MainActor in
isLoading = true
}
var url = NetworkManager.shared.baseUrl;
for p in path {
url = url.appending(path: p)
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONEncoder().encode(body)
// TODO: This should be handled with auth challenges
if let token = NetworkManager.shared.token {
request.setValue(token, forHTTPHeaderField: "Authorization");
}
// Set timezone header
request.setValue(TimeZone.current.identifier, forHTTPHeaderField: "TIMEZONE");
let (respData, response) = try await NetworkManager.shared.session.data(for: request)
if let token = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Authorization") {
NetworkManager.shared.token = token
}
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
Task { @MainActor in
isLoading = false
}
throw FetchError.badRequest
}
let temp = try JSONDecoder().decode(T.self, from: respData)
Task { @MainActor in
data = temp
isLoading = false
}
}
}




