Swift iOS Alamofire 数据在 viewDidLoad 中第一次返回空

问题描述 投票:0回答:1

我正在尝试将数据从 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

        }
    }

我在调用

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

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)
            
        }
    }
ios swift model-view-controller alamofire
1个回答
1
投票

您的

loadAdInfo
方法是异步的。

与使用completionHandler从

adsForSection
获取Alamofire的数据到
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"]
}
© www.soinside.com 2019 - 2024. All rights reserved.