How to Get the Result Value of Alamofire.Request().Responsejson in Swift 2

How to get the result value of Alamofire.request().responseJSON in swift 2?

The accepted answer works great but with the introduction of Alamofire 3.0.0 there are some breaking changes that affects this implementation.

The migration guide has further explanations but i will highlight the ones related to the actual solution.

  • Response

    All response serializers (with the exception of response) return a generic Response struct.

  • Response type

    The Result type has been redesigned to be a double generic type that does not store the NSData? in the .Failure case.

Also take in count that Alamofire treats any completed request to be successful, regardless of the content of the response. So you need to chain a .validate() before .responseJSON() to hit the .Failure case.
Read more about it here.

Updated code:

let url = "http://api.myawesomeapp.com"
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
let name = json["name"].stringValue
print(name)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

For reference:

  • Xcode 7.3 (Swift 2.2)
  • Alamofire 3.3.1
  • SwiftyJSON 2.3.3

Swift 2 - how to get data from Alamofire.responseJSON

storiesForSection:page:response has a callback function, just call it with the JSON object as parameter.

Alamofire.request(.GET, urlString, parameters: parameters).responseJSON { (response) -> Void in
let swiftyData = JSON(response.result.value ?? [])
response(swiftyData)
}

How to return value from Alamofire

As mattt points out, Alamofire is returning data asynchronously via a “completion handler” pattern, so you must do the same. You cannot just return the value immediately, but you instead want to change your method to not return anything, but instead use a completion handler closure pattern.

Nowadays, that might look like:

func getOrders(completionHandler: @escaping (Result<[String: Any]>) -> Void) {
performRequest("orders", completion: completionHandler)
}

func performRequest(_ section: String, completion: @escaping (Result<[String: Any]>) -> Void) {
let url = baseURL.appendingPathComponent(section)
let params = ["consumer_key": "key", "consumer_secret": "secret"]

Alamofire.request(url, parameters: params)
.authenticate(user: consumerKey, password: consumerSecret)
.responseJSON { response in
switch response.result {
case .success(let value as [String: Any]):
completion(.success(value))

case .failure(let error):
completion(.failure(error))

default:
fatalError("received non-dictionary JSON response")
}
}
}

Then, when you want to call it, you use this completion closure parameter (in trailing closure, if you want):

api.getOrders { result in
switch result {
case .failure(let error):
print(error)

case .success(let value):
// use `value` here
}
}

// but don't try to use the `error` or `value`, as the above closure
// has not yet been called
//

Alamofire JSON result parse with SwiftyJSON

Set content-type headers to application/json while requesting JSON request as below :

let headers = [
"Content-Type" : "application/json; charset=UTF-8"
]

let getRouteURL = "http://example.com/api/Trafi/GetRoute/"

Alamofire.request(getRouteURL,
method: HTTPMethod.post,
parameters: param,
encoding: JSONEncoding.default,
headers:headers).responseJSON{ response in

if let result = response.result.value {
if let JSON = try? JSON(result){
if let RoutesArr = JSON["Routes"].arrayObject{
self.routes = RoutesArr as! [[String : AnyObject]]
self.routeTable.reloadData()
}
}

}

}

Extract response data from api call in alamofire

You need to decode the jSON response, so create a Model to decode this, of course also check the response if it was successful before, you'll set an example:

Declare yourself a model:

struct RootResponse : Decodable {
var error: ErrorStruct
var payload: PayloadStruct
var success: Int
}

struct ErrorStruct: Decodable {
var code: String
var message: String
}

struct PayloadStruct : Decodable {
var ?
}

Once you've declared your model based on your jSON response, then you can switch to the function that makes the request to you:

AF.request("http://10.177.41.163:9000/signup",
method: .post,
parameters: parameters,
encoder: JSONParameterEncoder.default).responseJSON{ response in
print(response.result)

switch response.result {
case .success:
if let data = response.data {
print(data)
// Convert This in JSON
do {
let responseDecoded = try JSONDecoder().decode(RootResponse.self, from: data)
print("USER: ", responseDecoded.error.code, "Etc...")
}catch let error as NSError{
print(error)
}

}
case .failure(let error):
print("Error:", error)
}

}

I hope that's been helpful.

Xcode : Alamofire get String response

If you want JSON response use .responseJSON , if you want String response use .responseString. If you want both use both. Hope this help.

Alamofire.request(loginUrl, method: .post, parameters: parameters)
.responseJSON { response in
print("JSON:\(response.result.value)")
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}

case .failure(_):

print("Error message:\(response.result.error)")
break

}
}
.responseString { response in
print("String:\(response.result.value)")
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}

case .failure(_):
print("Error message:\(response.result.error)")
break
}
}

UPDATED: Swift 5, Alamofire 5

    AF.request(urlString, method: .post, parameters: parameters)
.responseJSON { response in
print("response: \(response)")
switch response.result {
case .success(let value):
print("value**: \(value)")

case .failure(let error):
print(error)
}
}
.responseString { response in
print("response: \(response)")
switch response.result {
case .success(let value):
print("value**: \(value)")

case .failure(let error):
print(error)
}
}

Not able to retrieve the exact queried response using Alamofire

I think something is going on with Alamofire package after archiving the project. I tried recreating the project and it worked fine until I archived the project to test on another device. So, I've switched over to urlRequest instead of using Alamofire request. Replacing Alamofire request with the below worked fine for me.

var urlRequest = URLRequest(url: URL(string: "https://mywesite.com/wp-json/wp/v2/posts?per_page=100")!)

let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in



Related Topics



Leave a reply



Submit