frostfat frostfat - 4 months ago 8
JSON Question

Swift: Return Type JSON from function

so I've got a function that needs to return a JSON object that is received from an API endpoint. For some reason, this function always returns nil, even though when I print the response.result.value, it contains the API response perfectly, and enters the if statement to assign to returnJSON. Would appreciate any input!

func storeContact(name: String, number: String, apiToken: String) -> AnyObject? {

var returnJSON: AnyObject?

let contact = ["api_token" : apiToken, "name" : name, "number": number]

Alamofire.request(.POST, "http://sample.app/api/v1/contact", parameters: contact, encoding: .JSON).responseJSON { (response) -> Void in

if let value = response.result.value {

returnJSON = value

}
}

return returnJSON

}

Answer

Alamofire use asynchronous calls, because internet fetches always need some times. Completion block of Alamofire.request always invoked after storeContact return it value. Its common to use closures in this situation:

func storeContact(name: String, number: String, apiToken: String, completeonClosure: (AnyObject?) -> ()) {
    let contact = ["api_token" : apiToken, "name" : name, "number": number]

    Alamofire.request(.POST, "http://sample.app/api/v1/contact", parameters: contact, encoding: .JSON).responseJSON {
        response in
        completeonClosure(response.result.value)
    }
}

Usage:

storeContact("name", number: "number", apiToken: "apiToken") {
    returnJSON in
    print(returnJSON)
}