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

时间:2015-06-09 14:06:16

标签: ios swift api model-view-controller alamofire

我正在尝试将API中的数据加载到我的viewcontroller中,但第一次加载数据时返回空

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)

        }
    }

1 个答案:

答案 0 :(得分:1)

您的loadAdInfo方法是异步的。

与使用completionHandler将Alamofire的数据从adsForSection传递到loadInfo的方式相同,您需要为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"]
}