所以我重复得到这个错误:
“字符0周围的值无效。”
我已经用尽了所有调试方法。基本上,API在Postman中运行良好,但是通过代码失败可怕。邮差在本地设置,因此我不能在这里分享。无论如何,这是我的代码:
let headers = ["Content-Type": "application/json",
"Accept": "application/json"]
let params = ["userId":"98", "candidateId":"4"]
Alamofire.request(url, method: .post, parameters: params, encoding:
JSONEncoding.default, headers: headers).response { response in
if let data = response.data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any]
completion(json , nil)
} catch {
completion(nil, response.error)
}
}else{
completion(nil, response.error)
}
}
我已经尝试过responseString,responseJSON和response以及JSONSerialization我使用了.allowFragments,.mutableContainers和.mutableLeaves的选项,但没有用。我甚至尝试过给它标题虽然Postman调用不包括标题但是再次失败。我该怎么办,请帮忙。以下是响应对象的快照:
这是我执行此操作后的responseString:
String(data: data, encoding: .utf8)
这是我删除.allowFragments时的错误:
Error Domain = NSCocoaErrorDomain Code = 3840“JSON文本没有以数组或对象开头,并且选项允许未设置片段。” UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}
POSTMAN CALL SNAPSHOT:
问题出在你的标题上
let headers = ["Content-Type": "application/json",
"Accept-Type": "application/json"]
Accept-Type
不是有效的HTTP标头。你需要的是Accept
let headers = ["Content-Type": "application/json",
"Accept": "application/json"]
就我而言:
更改内容类型标头
headers = [
"Content-Type": "application/json",
"Authorization" : "Token"
]
至
headers = [
"Content-Type": "application/x-www-form-urlencoded",
"Authorization" : "Token"
]
成功了!