I am working on a swiftui project where I need to post call a string of a specific date format to an API and retrieve response back from it.
Code as follows:
func createProfile(birthday: String, email: String, fullName: String, gender: String, completion: @escaping (Result<Bool, NetworkError>) -> Void) {
guard let url = URL(string: "*******") else {
completion(.failure(.invalidURL))
return
}
var request = URLRequest(url: url)
let defaults = UserDefaults.standard
guard let token = defaults.string(forKey: "jsonwebtoken") else {
return
}
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: String] = [
"birthday" : "02/01/2022",
"email": email,
"fullName": fullName,
"gender": gender
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
print(body)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
completion(.failure(.noData))
return
}
guard let profile = try? JSONDecoder().decode(ProfileResponse.self, from: data) else {
completion(.failure(.decodingError))
return
}
print(profile)
completion(.success(profile.activationStatus))
}.resume()
}
With no loggings the code just doesn't work and the app runs normally, with the next print statements:
print(String(data: data, encoding: .utf8))
The console logs:
Optional("{\"errors\":{\"message\":\"parsing time \\\"\\\\\\\"02\\\\\\\\/01\\\\\\\\/2022\\\\\\\"\\\" as \\\"\\\\\\\"02/01/2006\\\\\\\"\\\": cannot parse \\\"\\\\\\\\/01\\\\\\\\/2022\\\\\\\"\\\" as \\\"/\\\"\"}}\n")
Also when printing the request's body it is as expected:
["birthday": "02/01/2022", "fullName": "Samy", "email": "hello.world@gmail.com", "gender": "Male"]
@Larme 's answer and link suggestion helped me fix my code error, all the thanks to him:
Unrelated but: .fragmentsAllowed is not needed. The issue is that it will add a backslash before slashes in a String. It's valid JSON, but it seems to be an issue with that with your server parsing. print(body)
is misleading, what you want to see is the JSON sent:
print(String(data: request.httpBody!, encoding: .utf8)!)
See stackoverflow.com/questions/47076329 with Codable, but limited to iOS13+ it seems. But you might have a hint/lead to search...