Handle JSON Response with Alamofire in Swift

Handling Json response with alamofire

Use above code:-

func CallAPI(){

let parameters: [String: Any] = [
"Username": "Admin",
"Password": "123456",
"Language_Code": "EN"]

Alamofire.request("Your API Url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in

if((response.result.value) != nil) {

let ResultJson = JSON(response.result.value!)

print("ResultJson==",ResultJson)

let UserCount = ResultJson["users"].count

if UserCount > 0 {

// Do with your above code

let Email = ResultJson["users"]["email"].stringValue
let id = ResultJson["users"]["id"].intValue
let money = ResultJson["users"]["money"].intValue
let password = ResultJson["users"]["password"].stringValue
let username = ResultJson["users"]["username"].stringValue
}
}
}
}

How I can parse JSON with alamofire

Your response is a JSON Object known as Dictionary, use following line

let itemObject = response.result.value as? [String : Any]

go ahead with parsing inner array items

if let array = itemObject?["items"] as? [[String : Any]] {
for dict in array {
guard
let id = dict["id"] as? Int,
let name = dict["name"] as? String,
let owner = dict["owner"] as? [String : Any],
let ownerId = owner["id"] as? Int

else {
print("Error parsing \(dict)")
continue
}

print(id, ownerId, name)
}
}

Instead of parsing JSON manually, use Codable with Alamofire's responseData, below is an example

struct Item: Decodable {
let id: Int
let name: String
let owner: Owner
}
struct Owner: Decodable {
let id: Int
let login: String
}
struct PageData: Decodable {
let totalCount: Int
let incompleteResults: Bool
let items: [Item]

enum CodingKeys: String, CodingKey {
case totalCount = "total_count"
case incompleteResults = "incomplete_results"
case items
}
}

Alamofire.request("URL").responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
do {
let pageData = try JSONDecoder().decode(PageData.self, from: data)
print(pageData, pageData.items.first?.name ?? "", pageData.items.first?.owner.id ?? 0)
} catch let error {
print(error)
}
}
}

How to parse JSON response to Model struct from Alamofire in Swift 5?

Assuming your RegisterResponse is Decodable, simply use responseDecodable:

AF.request(registerUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
.responseDecodable(of: RegisterResponse.self) { response in
// Handle response.
}

Handle JSON Response with Alamofire in Swift

In the first click, the code

return self.jsonString

will run before

.response {
(request, response, data, error) -> Void in

let json = JSONValue(data as? NSData)
self.jsonString = json.rawJSONString
}

you will get nil form the self.jsonString in the first time, you second click will get the first click's request data.

If you use SwiftyJSON and Alamofire you can try Alamofire-SwiftyJSON

How to handle Alamofire Response in ios swift 4?

Create data types for the response json as below and use JSONDecoder to parse the response.

// MARK: - PostBody
struct PostBody: Codable {
let responsePayload: ResponsePayload

enum CodingKeys: String, CodingKey {
case responsePayload = "ResponsePayload"
}
}

// MARK: - ResponsePayload
struct ResponsePayload: Codable {
let statusData: StatusData

enum CodingKeys: String, CodingKey {
case statusData = "StatusData"
}
}

// MARK: - StatusData
struct StatusData: Codable {
let statusCode: String
let status: String
let documents: [Document]

enum CodingKeys: String, CodingKey {
case statusCode = "StatusCode"
case status = "Status"
case documents = "Documents"
}
}

// MARK: - Document
struct Document: Codable {
let docname: String
let isUploaded: String

enum CodingKeys: String, CodingKey {
case docname = "docname"
case isUploaded = "isUploaded"
}
}

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseData { response in
switch response.result {
case .success(let data):
do {
let postBody = try JSONDecoder().decode(PostBody.self, from: data)
print(postBody.responsePayload.statusData.statusCode)
print(postBody.responsePayload.statusData.documents.map { $0.docname })
} catch {
print(error)
}
case .failure(let error):
print(error)
}
}


Related Topics



Leave a reply



Submit