here is the function , and in postman when I put Accept-Language “en” it get the data in English , but my code not , why
func fetchDataByToken<T: Decodable>(urlString: String, type: T.Type) -> AnyPublisher<T, APIError> {
guard let token = UserManager.shared.getToken() else {
return Fail(error: APIError.serverError)
.eraseToAnyPublisher()
}
guard let url = URL(string: urlString) else {
return Fail(error: APIError.invalidURL)
.eraseToAnyPublisher()
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("en", forHTTPHeaderField: "Accept-Language")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer (token)", forHTTPHeaderField: "Authorization")
return URLSession.shared.dataTaskPublisher(for: request)
.tryMap { output -> Data in
guard let response = output.response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else {
throw APIError.invalidData
}
return output.data
}
.decode(type: T.self, decoder: JSONDecoder())
.mapError { _ in
APIError.invalidData
}
.eraseToAnyPublisher()
}
I want the data to be in English
1
You probably have a mismatch between the URL request you’re sending from your app versus the URL request you’re sending with Postman. You can use the Network Instrument from Xcode (on a real device only, not the Simulator) to see the exact request as it goes out. See documentation at
https://developer.apple.com/documentation/foundation/url_loading_system/analyzing_http_traffic_with_instruments.
I personally prefer Proxyman for this sort of network tracing, because I can capture and analyze traffic on any device without having an Xcode session connected to the device. See https://proxyman.io.
Also, if there’s any way you can swing it, I suggest you use async/await instead of Combine. Combine, in my experience, is hard to read, hard to debug, and hard to write tests for; it seems to have been relegated and most new code uses async/await instead, where possible.