我正在开发一个 swiftui 项目,我需要将特定日期格式的字符串调用发布到 API 并从中检索响应。
代码如下:
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()
}
如果没有日志记录,代码将无法工作,并且应用程序可以正常运行,并显示以下打印语句:
print(String(data: data, encoding: .utf8))
控制台日志:
Optional("{\"errors\":{\"message\":\"parsing time \\\"\\\\\\\"02\\\\\\\\/01\\\\\\\\/2022\\\\\\\"\\\" as \\\"\\\\\\\"02/01/2006\\\\\\\"\\\": cannot parse \\\"\\\\\\\\/01\\\\\\\\/2022\\\\\\\"\\\" as \\\"/\\\"\"}}\n")
打印请求正文时也符合预期:
["birthday": "02/01/2022", "fullName": "Samy", "email": "[email protected]", "gender": "Male"]
@Larme 的回答和链接建议帮助我修复了我的代码错误,这一切都归功于他: 不相关,但是:不需要 .fragmentsAllowed。问题是它会在字符串中的斜杠之前添加反斜杠。它是有效的 JSON,但它似乎是您的服务器解析的问题。
print(body)
有误导性,你想看到的是发送的JSON:
print(String(data: request.httpBody!, encoding: .utf8)!)
参见 stackoverflow.com/questions/47076329 with Codable,但似乎仅限于 iOS13+。但你可能会有搜索的提示/线索...