【发布时间】:2015-11-06 12:37:10
【问题描述】:
我刚刚开始完全掌握 iOS 开发和 Xcode,我正在使用 Swift 2 学习它。我正在尝试从 URL 获取一些 JSON 数据,将其拆分为 swift Array,并将其显示在TableView 中。我已设法将 JSON 数据拆分为 Array,但我无法重新加载表的数据以使其显示。这是我的代码:
//
// ViewController.swift
// Table JSON
//
// Created by James Allison on 06/11/2015.
// Copyright © 2015 James Allison. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var cellContent = ["this should be replaced","something","something else"]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// construct url
let url = NSURL(string: "http://127.0.0.1:8888/json.php")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
// the following will happen when the task is complete
if let urlContent = data {
var webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
// remove []
webContent = webContent?.stringByReplacingOccurrencesOfString("[", withString: "")
webContent = webContent?.stringByReplacingOccurrencesOfString("]", withString: "")
// split by commas
var webContentArr = webContent?.componentsSeparatedByString(",")
var temp = ""
// remove quote marks
for var i = 0; i < webContentArr!.count; i++ {
temp = webContentArr![i]
temp = temp.stringByReplacingOccurrencesOfString("\"", withString: "")
webContentArr![i] = temp
}
print(webContentArr!)
self.cellContent = webContentArr! as! Array
self.table.reloadData()
}
else {
// something failed
print("Error: invalid URL or something.")
}
}
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellContent.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = cellContent[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在我运行它的那一刻,表格显示原始的cellContent 变量,但不是新的变量。没有产生错误,并且数组打印正常。
编辑:感谢 Joshua 的回答。我最终使用以下代码来解决我的问题:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.cellContent = webContentArr! as! Array
self.table.reloadData()
})
【问题讨论】:
标签: ios arrays json swift swift2