Swift ios alamofire数据第一次在viewDidLoad返回空



我试图从API加载数据到我的视图控制器,但第一次加载数据返回空

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
        }
    }

在调用"println(adInfo)"之前,我正在运行"loadAdInfo()",但它仍然显示为空数组

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)
        }
    }

您的loadAdInfo方法是异步的。

以同样的方式,你使用一个completionHandler来获得Alamofire的数据从adsForSectionloadInfo,你需要为loadInfo做一个处理程序,这样你就可以检索异步响应。

像这样:

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

在你的viewDidLoad中:

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

最新更新