ios - Wait for multiple Alamofire request -
i'm trying add data data model test i'm printing info fetched via alamofire problem since data needs call api again becomes null when print it. here's code
code getting person's data
func printapi(){ swapihandler.requestswpapi("http://swapi.co/api/people", completionhandler: {(response, error) in let json = json(response!) let jsonresult = json["results"] (index,person):(string, json) in jsonresult{ let name = person["name"].stringvalue let height = person["height"].intvalue let mass = person["mass"].intvalue let haircolor = person["hair_color"].stringvalue let skincolor = person["skin_color"].stringvalue let eyecolor = person["eye_color"].stringvalue let birthyear = person["birth_year"].stringvalue let gender = person["gender"].stringvalue let homeworldurl = person["homeworld"].stringvalue let homeworldnamekey = "name" let homeworld = self.getswapispecificvalue(homeworldurl, strkey: homeworldnamekey) print("name: \(name)") print("height: \(height)") print("mass: \(mass)") print("hair color: \(haircolor)") print("skin color: \(skincolor)") print("eye color: \(eyecolor)") print("birth year: \(birthyear)") print("gender: \(gender)") print("home world: \(homeworld)") print("------------------------------") } }) }
code getting specific value
func getswapispecificvalue(strurl: string, strkey: string) -> string{ var name = "" swapihandler.requestswpapi(strurl, completionhandler: {(response,error) in let json = json(response!) print(json[strkey].stringvalue) name = json[strkey].stringvalue }) return name }
if want know json model here is
you should make api call in background , after it's finished populate data on main queue. change code specific value one:
func getswapispecificvalue(strurl: string, strkey: string) -> string{ var name = "" dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_background, 0)) { () -> void in swapihandler.requestswpapi(strurl, completionhandler: {(response,error) in dispatch_async(dispatch_get_main_queue()) { let json = json(response!) print(json[strkey].stringvalue) name = json[strkey].stringvalue return name } }) } }
in code above first make request server in background
, if response in main
queue populate variable name
. it's better change api call function that:
func getdatafromserver(ulr: string, success: (([anyobject]) -> void)?, failure: (error: errortype) -> void){ }
in way can handle errors , if success data.
Comments
Post a Comment