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

时间:2018-12-28 05:12:45

标签: json swift get alamofire

当我想使用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 $ CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS       128       [“ id”:“ 128”,“ Authorization”:“ $ 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附近的无效值。)))

2 个答案:

答案 0 :(得分: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?)!)
                    }
            }

答案 1 :(得分:0)

您可以像这样使用它来创建标题

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): } }