Hello,
I am having an issue with my request response only containing a partial response body despite the request having a 200 http response status.
When I print out the raw response without parsing it to JSON I can see that the content is truncated (leading to an invalid JSON).
I am unable to reproduce the same issue on Postman, so this seems to be isolated to my ios app (I have had the same issue with the endpoint in React Native as well).
Any tips or suggestions would be appreciated!
(Excuse the code, learning swift as I go)
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)
let json = String(data: respData, encoding: String.Encoding.utf8)
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
}
}
}
class NetworkManager{
static let shared = NetworkManager(baseUrl: "https://my-api-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)
}
}