[ad_1]
Once I use URLSession
in a Swift iOS app to fetch knowledge from my server I get a 200 response, however the response physique is incomplete (it seems to be truncated, resulting in an invalid json). Once I make the identical request on Postman it really works as anticipated, returning the complete response physique, so the problem appears to be remoted to iOS.
I’m not certain what steps to take subsequent to debug the problem. Any assist or ideas can be appreciated.
class NetworkManager{
static let shared = NetworkManager(baseUrl: "https://my-url.com");
let baseUrl: URL
let session: URLSession
var token: String?
personal init(baseUrl: String) {
// TODO: Throw properly outlined error
self.baseUrl = URL(string: baseUrl)!
let configuration = URLSessionConfiguration.default
self.session = URLSession(configuration: configuration)
}
}
class Fetcher<T, G>: ObservableObject the place T: Decodable, G: Codable {
@Revealed var knowledge: T? = nil
@Revealed var isLoading: Bool = false
public var path: [String] { return [] }
func fetchData(physique: G) async
throws {
Job { @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("utility/json", forHTTPHeaderField: "Content material-Kind")
request.httpBody = strive? JSONEncoder().encode(physique)
// TODO: This must be dealt with with auth challenges
if let token = NetworkManager.shared.token {
request.setValue(token, forHTTPHeaderField: "Authorization");
}
// Set timezone header
request.setValue(TimeZone.present.identifier, forHTTPHeaderField: "TIMEZONE");
let (respData, response) = strive await NetworkManager.shared.session.knowledge(for: request)
if let token = (response as? HTTPURLResponse)?.worth(forHTTPHeaderField: "Authorization") {
NetworkManager.shared.token = token
}
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
Job { @MainActor in
isLoading = false
}
throw FetchError.badRequest
}
let temp = strive JSONDecoder().decode(T.self, from: respData)
Job { @MainActor in
knowledge = temp
isLoading = false
}
}
}
[ad_2]