如何使用标头从服务器Alamofire swift获取数据

问题描述 投票:-1回答:2

当我想使用Alamofire从服务器获取数据时,它向我显示了一些错误,我希望使用头文件中的标头从服务器获取数据我传递id和令牌。

@IBAction func profile(_ sender: Any) {

    print(AuthService.instance.authToken)
    print(AuthService.instance.userEmail)
    let BEARER_HEADER2 = [
        "id":AuthService.instance.userEmail,
        "Authorization":AuthService.instance.authToken

        //"Content-Type": "application/json; charset=utf-8"
    ]
    print(BEARER_HEADER2)

    Alamofire.request("http://fiveorzero.ml/api/v1/user/user/profile",method: .get, parameters: nil,encoding:URLEncoding.default, headers: BEARER_HEADER2).responseJSON { response in
        switch response.result {
        case .success(let value):
            let swiftyJson = JSON(value)
            print(swiftyJson)
            print("Khabbab")

        case .failure(let error):
            debugPrint(response.result.error as Any)
            print ("error: \(error)")
        }
    }

}

$ 2Y $ 10 $ 128 CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS [ “ID”: “128”, “授权”: “$ 2Y $ 10 $ CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS”]可选(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域= NSCocoaErrorDomain代码= 3840 “字符0周围的值无效。”UserInfo = {NSDebugDescription =字符0周围的值无效。})))错误:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域= NSCocoaErrorDomain代码= 3840“字符0周围的值无效” UserInfo = {NSDebugDescription =字符0周围的值无效。}))

json swift get alamofire
2个回答
0
投票

试试这样吧

 Alamofire.request(URL, method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON
                {
                    response in
                    switch response.result
                    {
                    case .success(let value):
                        completionHandler(value as? Array, nil)//completionHandler(value as? NSDictionary, nil)
                    print(value)
                    case .failure(let error):
                        completionHandler(nil,(error as NSError?)!)
                    }
            }

0
投票

您可以像这样使用create header

let id = "your id"
let Authorization = "your ascess token"
let credentialData = "\(id):\(Authorization)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

Alamofire.request("your url" , method : .post, parameters: parameters,
                      headers: headers)
        .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .failure(let error): break
        // self.popupp(elrtdata : "Please try again latter.")
        case .success(let responseObject): } }
© www.soinside.com 2019 - 2024. All rights reserved.