Pass token with post request using Alamofire - swift

I'm new to iOS and I would like some direction on why my code isn't working. I'm trying to make a call to a url and pass a token and get the response. My response is coming back with a 404 status code.
let reverse = ["token": "831b21c47a7f7daee7d6e4e3fa11deaa"]
let url = "http://challenge.com"
Alamofire.request(url, parameters: reverse).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

Try bellow code:
Alamofire.request(url, method: .get, parameters: reverse, encoding: JSONEncoding.default).responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

Try this Code:
This code is also handle the error when response will be the blank and also the Internet connection is disable.
func apiCall(params : [String:AnyObject],block:([String:AnyObject]->Void)?) {
if Reachability.isConnectedToNetwork(){
Alamofire.request(.POST, URL, parameters: params, encoding: .JSON, headers: nil).responseJSON{
response in
let data = response.result.value
if data == nil{
if response.result.error?.code == -1005 {
print(response.result.error?.localizedDescription)
}
else{
switch response.result {
case .Success:
block!(data as! [String:AnyObject])
case .Failure(let error):
print(error)
}
}
}
}
else{
print(NO_NETWORK)
}
}

Related

JSONSerialization swift response is always nil

I'm performing a post request over my rest api that I built in node. Then the data are stored in a mongodb collection.
This is my code that I use to post the request:
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: ErrorHandler] {
print(jsonResponse)
DispatchQueue.main.async {
self?.isLoading = false
self?.signedIn = true
}
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
task.resume()
The problem is that the responseJson is always nil. I tried to perform the same request with postman and I get the response correctly. What is the problem? Also because the data are correctly uploaded everywhere.
This is my postman result of the same post request.

API working in Postman but giving error in Code

I am trying to call API in postman and its working fine, But If I am trying to call API in swift Alamofire, Its give me error-
My Code is-
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data: Parameters = ["SerialNo": "T8180399","Status":101]
Alamofire.request(urlString, method: .post, parameters: data,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
Error is-
The JSON value could not be converted to System.Collections.Generic.List`1[BreakBulkModels.Model.WebapiModels.DtoInventoryApi]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Your API accepts as parameters an array of JSON objects but you are currently sending a JSON object:
{
"SerialNo": "T8180399",
"Status": 101
}
Because Parameters is a typealias to Dictionary<String, Any> (what you need is Array<Dictionary<String, Any>>) you have to do your parameter encoding yourself and then call request(_:) function of Alamofire passing your URLRequest:
do {
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let url = try urlString.asURL()
var request = URLRequest(url: url)
let data = [["SerialNo": "T8180399", "Status": 101]]
request = try JSONEncoding.default.encode(request, withJSONObject: data)
Alamofire.request(request).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
} catch {
print(error)
}
Edit: With Alamofire v5 there is a more elegant way by using Encodable protocol:
struct BarCode: Encodable {
var SerialNo: String
var Status: Int
}
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data = [BarCode(SerialNo: "T8180399", Status: 101)]
AF.request(
urlString,
method: .post,
parameters: data,
encoder: JSONParameterEncoder.default
).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}

How do I trace the response of this call in Swift Xcode?

Data in the below call is nil so the call is failing:
postRequest("/api/users/signup", params: params, headers: nil) { data in
guard data != nil else {
return completionHandler(nil, UsersStoreError.CannotSignup)
This is the postRequest function:
private func postRequest(_ url: String, params: Parameters?, headers: HTTPHeaders?, completion: #escaping([String:Any]?) -> Void) {
let enc = JSONEncoding.default
let url = AppConstants.ENDPOINT + url
Alamofire
.request(url, method: .post, parameters:params, encoding:enc, headers:headers)
.validate()
.responseJSON { response in
switch (response.result) {
case .success(let data): completion((data as! [String:Any]))
case .failure(_): completion(nil)
}
}
}
How can I trace the response of this call?
Set a breakpoint in the responseJSON block in your postRequest method and inspect/print the response parameter. That should give you information about the request and the response.
It's possible that the response isn't valid JSON. To check what you're actually getting back, add this to responseJSON (before your switch):
debugPrint(String(data: response.data!, encoding: .utf8))

ios swift 3 Alamfire post request issue

enter image description hereenter image description hereenter image description hereI am using Alamofire. I am stuck in posting the post request.
I have a post body which is -
[
{
"siteName": "lab1",
"locationCode": "111",
"locationName": "test1"
}
]
How should I make the request call? I am doing -
let parameters: Parameters = [
"siteName": "lab",
"locationCode": "1156",
"locationName": "123test"
]
Alamofire.request(URLStr, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
sucessHandler(json)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
failureHandler(response.error)
}
}
Thank you so much guys. I found the other way of doing this.
let fileUrl = NSURL(string: URLStr)
var request = URLRequest(url:fileUrl as! URL )
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = [parameters]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
failureHandler(response.error)
}
case .success(let responseObject):
print(responseObject)
do {
let user = try IeroLocationSave(JSONDecoder(response.data ?? "nil..12"))
//print("city is: \(user.address.city)")
sucessHandler(user)
//That's it! The object has all the appropriate properties mapped.
} catch {
print("unable to parse the JSON")
}
}
}
Below code works for me
let parameters: Parameters = ["feedback_name": "SwiftTest","feedback_email":"m#m.com","feedback_description":"Test"]
Alamofire.request("http://212.69.45.77:8082/api/feedbackapp",method: .post,parameters: parameters).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}

Alamofire GET request parameters

When send GET request with parameters, url encoded in a different way
http://someurl/search-ads?attributes[elevator]=1&attributes[ranges][square][]=20.0&attributes[ranges][square][]=170.0&cities[]=somecity&currency=kgs&has_images=0&not_first_floor=1&not_last_floor=1&order_type=sale&rating__gte=5&rating__lte=10000&specialty=2
but it should be
http://someurl/search-ads?specialty=7&order_type=sale&attributes={"ranges":"{\"square\":[2450,8190]}"}&cities=somecity&page=1
Is there any settings to change, to force Alamofire to encode in second way?
I am using Alamofire 3
Here is my method
func makeSearch(search: GeneralSearch) {
let request = Alamofire.request(.GET, SearchURL, parameters: Mapper().toJSON(search), encoding: .URL).validate().responseJSON {
response in
switch response.result {
case .Success:
if let responseValue = response.result.value {
print(responseValue)
}
break
case .Failure(let error):
print("Error: " + error.localizedDescription)
break
}
}
}