Reputation: 5832
I want to Handle work with JSON response in Swift lang, I use 3 pod in my project : Alamofire
- ObjectMapper
- AlamofireObjectMapper
And when http request send I want have JSON in my Object class. without trouble. and here is my code.
Contact.swift class:
import Foundation
import ObjectMapper
class Name: Mappable {
var title: String!
var first: String!
var last: String!
required init?(_ map: Map) {
}
func mapping(map: Map) {
title <- map["title"]
first <- map["first"]
last <- map["last"]
}
}
class ContactsResponse: Mappable {
var gender: String!
var nameFull: [Name]?
required init?(_ map: Map) {
}
func mapping(map: Map) {
gender <- map["gender"]
nameFull <- map["name"]
}
}
ViewController.swift :
let baseURL = "http://api.randomuser.me/"
override func viewDidLoad() {
super.viewDidLoad()
makeHTTPRequest()
}
func makeHTTPRequest() {
Alamofire.request(.GET, baseURL).responseObject { (response: Response<ContactsResponse, NSError>) in
let contactResponse = response.result.value
print(contactResponse?.gender) // print Nil :(
}
}
But when i build project print nil
instead of Male or female for gender!
Whats wrong in my code?
Upvotes: 0
Views: 2855
Reputation: 301
This maybe a delayed response but try checking your "keys" for a mistake. Narrow down on the source of your problem. So first check if response.result.value is giving you a response.
If i'm right, either response.result.value == nil or your mapping of the keys "gender" is wrong.
I'd recommend you to use if let statements instead of let.
so for example
if let contactResponse = response.result.value {
print(contactResponse?.gender)
} else {
//Handle error
}
Upvotes: 2