【发布时间】:2018-03-26 16:46:52
【问题描述】:
我知道在手动将数据添加到数组时如何保存复选标记。我只是不知道当数据与 API 同步时如何保存单元格的复选标记属性。
这是我的代码:
class TableViewController: UITableViewController {
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist")
var fetchCoinInfo = [[String: AnyObject]]()
let url = "https://api.coinmarketcap.com/v1/ticker/"
override func viewDidLoad() {
super.viewDidLoad()
getCoinData(url: url)
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return fetchCoinInfo.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = fetchCoinInfo[indexPath.row]["name"] as? String
cell.detailTextLabel?.text = fetchCoinInfo[indexPath.row]["symbol"] as? String
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell?.accessoryType == .checkmark {
cell?.accessoryType = .none
}else {
cell?.accessoryType = .checkmark
}
}
func getCoinData(url: String) {
// Alamofire parsing code:
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the data")
let coinJSON : JSON = JSON(response.result.value!)
print(coinJSON)
self.updateCoinData(json: coinJSON)
} else {
print("Error: \(String(describing: response.result.error))")
}
}
self.tableView.reloadData()
}
// SwiftyJSON code:
func updateCoinData(json : JSON) {
if let coinSymbol = json[].arrayObject {
print(coinSymbol)
self.fetchCoinInfo = coinSymbol as! [[String: AnyObject]]
}
else {
print("cannot connect to the server")
}
self.tableView.reloadData()
}
}
【问题讨论】:
标签: swift xcode alamofire swifty-json