我正在尝试将数据从 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)
}
}
您的
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"]
}