我正在尝试将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)
}
}
答案 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"]
}