Alamofire字符0附近的值无效|迅捷4

时间:2018-11-08 14:32:57

标签: ios swift alamofire xcode10

所以我反复出现此错误:

  

“字符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调用不包含标头,但再次失败了。我该怎么办,请帮忙。下面是响应对象的快照:

enter image description here

这是我执行此操作后获得的responseString即时消息:

String(data: data, encoding: .utf8)

&这是我删除.allowFragments时的错误:

  

Error Domain = NSCocoaErrorDomain代码= 3840“ JSON文本未启动   带有数组或对象,并具有允许未设置片段的选项。”   UserInfo = {NSDebugDescription = JSON文本不是以数组开头或   对象和允许未设置片段的选项。}

邮递员电话快照:

enter image description here

2 个答案:

答案 0 :(得分:0)

问题出在您的标题上

let headers = ["Content-Type": "application/json",
                "Accept-Type": "application/json"]

Accept-Type不是有效的HTTP标头。您需要的是Accept

let headers = ["Content-Type": "application/json",
                     "Accept": "application/json"]

答案 1 :(得分:0)

就我而言:

更改内容类型的标头

 headers = [
        "Content-Type": "application/json",
        "Authorization" : "Token"
    ]

收件人

 headers    = [
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization" : "Token"
        ]

工作!