Elia Crocetta
Elia Crocetta

Reputation: 368

Alamofire 4 get request something wrong

I have to make this get request

curl --request GET \
  --url http://site.exampleTest \
  --header 'authorization: longtoken'

so I've made this function:

    class func getRequest(endPoint: String, headers: [String : String], success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

        Alamofire.request(myBaseURL + endPoint, headers: headers).responseJSON { (responseObject) in
            print(responseObject)

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error = responseObject.result.error!
                failure(error as NSError)
            }
        }

    }

and I launch it like this:

let headerRequest = ["authorization":getUserDefaultElement(key: "token")]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
            print(JSONObject.debugDescription)
        }, failure: { (error)  in
            print(error)
        })

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) Error Domain=Alamofire.AFError Code=4 "JSON could not be serialized because of error: The data couldn’t be read because it isn’t in the correct format."

With the same token I have no errors in postman, so where am I wrong?

edit

my get should be this

    {
      "data": [
        {
         stuff in here
         } 
       ]
    }  

edit 2

here's the swift way, picked from postman in which i get 200 OK:

let headers = [
  "authorization": "token" //modified by me
]

let request = NSMutableURLRequest(url: NSURL(string: "http://link.api.me")! as URL, //modified by me
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

Upvotes: 0

Views: 1450

Answers (1)

Nevin Jethmalani
Nevin Jethmalani

Reputation: 2826

Give this a try. I believe you weren't putting the headers in the right format.

class func actualReq() {
    let headerRequest: HTTPHeaders = [
        "authorization":getUserDefaultElement(key: "token")
    ]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
        print(JSONObject.debugDescription)
    }, failure: { (error)  in
        print(error)
    })
}

class func getRequest(endPoint: String, headers:HTTPHeaders, success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

    Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        switch response.result {
        case .success(let value):
            let swiftyJson = JSON(value)
            print(value)
            success(resJson)
        case .failure(let error):
            print("Error: \(error)")
            failure(error as NSError)

        }
    }
}

Another method:

Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        if response.response?.statusCode == 200 {
            print ("success")
        }else {
            guard let responseCode = response.response?.statusCode else {return}
            print ("code: \(responseCode)")
        }
    }
}

Upvotes: 1

Related Questions