[英]SWIFT2: JSON request to array returns different values
我正在使用Alamofire和SwiftyJSON將JSON數據傳遞到數組。
第一次打印返回正確的數組:
[(1, "Arena", "Oklahoma"), (2, "Stafium", "Berlin")]
但是第二個打印一個空數組:
[]
我不明白為什么?
這是我的代碼。 由@NickCatib解決
typealias cType = (ID: Int,Tag: String, Location: String)
var cBlue = [cType]()
var NumRows = 0
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, url, parameters: ["postType": "live"]).responseJSON { (_, _, result) in
switch result {
case .Success(let data):
let json = JSON(data)
for(_,subJSON) in json["LocalInfo"] {
let ID = subJSON["id"].int!
let Tag = subJSON["Tag"].string!
let Location = subJSON["Location"].string!
let Info = (ID: ID, Tag: Tag, Location: Location)
cBlue.append(Info)
}
self.tableView.reloadData()
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
reloadUI()
return cBlues.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CellConcert",
forIndexPath: indexPath)
let info = cBlue[indexPath.row] as! Info
cell.textLabel?.text = info.Tag
return cell
}
}
這個對嗎?
謝謝
從總體上說,這很簡單:第二張打印將在Alamofire請求完成之前執行Alamofire.request
是異步調用,稍后將執行。
您將在請求后relaodData()
信息,並且如果需要設置一些UI元素,則在使用UITableView
必須調用某種重載視圖或relaodData()
。
您可以在此處調用自定義函數reloadUI()
:
//PRINTS THE ARRAY
reloadUI()
print(cBlue)
例:
類MainViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, url, parameters: ["postType": "live"]).responseJSON { (_, _, result) in
switch result {
case .Success(let data):
let json = JSON(data)
for(_,subJSON) in json["LocalInfo"] {
let ID = subJSON["id"].int!
let Tag = subJSON["Tag"].string!
let Location = subJSON["Location"].string!
let Info = (ID: ID, Tag: Tag, Location: Location)
cBlue.append(Info)
}
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
//PRINTS THE ARRAY
reloadUI()
print(cBlue)
}
//PRINT [] EMPTY ARRAY
print(cBlue)
}
}
func reloadUI(){
self.tagLabel.text = (cBlue[0] as! Info).tag
self.locationLabel.text = (cBlue[0] as! Info).location
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.