beka.angsabay beka.angsabay - 11 months ago 213
Swift Question

alamofire get request return null value

I have one problem. I am reuesting with alamofire an it return value. In alamofire i convert returned json to my custom class, its work goog. But when i am using this converted class out of alamofire body it returned nil value.
I put breakpoint in alamofire where i converted json value and appent to my class, it has value and it put it to my class.But out of body it equal nil. Why?

func getZakazDetail(orderID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){

if flag{
let zD=ZakazDetailTableViewController()
Alamofire.request(.GET, "myUrl")
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /todos/1")

if let value = response.result.value {
let product = JSON(value)
if product != nil{
for (_,subJson):(String, JSON) in product {
let p=ZakazDetail(id: subJson["id"].int!, tovar: subJson["tovar"].string!, count: subJson["count"].int!, orderid: subJson["orderid"].int!, cena: subJson["cena"].int!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false

let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!",delegate: nil,cancelButtonTitle: "OK")



This is happening because alamofire loads the data asynchronously and before you append anything in zD.detail.append(p). Add a completion handler for the program to wait till the loading is complete.

//here you call authenticateUser with a closure that prints responseObject
API().authenticateUser{ (responseObject, error) in


//authenticateUser receives your closure as a parameter
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
    //it passes your closure to makeAuthenticateUserCall

//makeAuthenticateUserCall receives your closure
func makeAuthenticateUserCall(completionHandler: (responseObject: String?, 
error: NSError?) -> ()) {
    Alamofire.request(.GET, loginUrlString)
        .authenticate(user: "a", password: "b")
        //here you pass a new closure to the responseString method
        .responseString { request, response, responseString, responseError in
            //in this closure body you call your completionHandler closure with the 
            //parameters passed by responseString and your code gets executed 
            //(that in your case just prints the responseObject)
            completionHandler(responseObject: responseString as String!, error: responseError)

For more information read the documentation: Swift Closures