Swift ios alamofire data returning empty first time in viewDidLoad

721 Views Asked by At

I am trying to load data from an API into my viewcontroller but the first time it loads the data returns empty

import UIKit

class AdViewController: UIViewController {

    var adId: Int!

    var adInfo: JSON! = []

    override func viewDidLoad() {
        super.viewDidLoad()

        loadAdInfo(String(adId),page: 1)

        println(adInfo)  // This shows up as empty

    }



    func loadAdInfo(section: String, page: Int) {
        NWService.adsForSection(section, page: page) { (JSON) -> () in
            self.adInfo = JSON["ad_data"]

            println(self.adInfo) // This shows up with data

        }
    }

I am running "loadAdInfo()" before I call "println(adInfo)" but it still shows up as an empty array

adsForSection:

static func adsForSection(section: String, page: Int, response: (JSON) -> ()) {
        let urlString = baseURL + ResourcePath.Ads.description + "/" + section
        let parameters = [
            "page": toString(page),
            "client_id": clientID
        ]
        Alamofire.request(.GET, urlString, parameters: parameters).responseJSON { (_, res, data, _) -> Void in
            let ads = JSON(data ?? [])
            response(ads)

            if let responseCode = res {
                var statusCode = responseCode.statusCode
                println(statusCode)
            }

            println(ads)

        }
    }
1

There are 1 best solutions below

1
On BEST ANSWER

Your loadAdInfo method is asynchronous.

In the same way you're using a completionHandler to get Alamofire's data from adsForSection to loadInfo, you need to make an handler for loadInfo so you can retrieve the asynchronous response.

Something like this:

func loadAdInfo(section: String, page: Int, handler: (JSON) -> ()) {
    NWService.adsForSection(section, page: page) { (JSON) -> () in
        handler(JSON)
    }
}

And in your viewDidLoad:

loadAdInfo(String(adId), page: 1) { handled in
    println(handled["ad_data"])
    self.adInfo = handled["ad_data"]
}