Swift 3 / Alamofire:无法用数据加载表格
Posted
技术标签:
【中文标题】Swift 3 / Alamofire:无法用数据加载表格【英文标题】:Swift 3 / Alamofire: Cant load the table with the data 【发布时间】:2017-06-30 04:58:04 【问题描述】:我正在尝试在 UItableview 上加载数据,我能够看到在输出面板中获取的记录,但无法在 UItableview 上获取它们。
请在下面找到代码:
import UIKit
import Alamofire
import SwiftyJSON
class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate
var tableData = Array<Category>()
var arrRes = [[String:AnyObject]]() //Array of dictionary
var category = [Category]()
var catTitle = ""
var id = ""
@IBOutlet weak var catTitleRec: UILabel!
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad()
super.viewDidLoad()
catTitleRec.text = catTitle
loadCategories(id:id)
func loadCategories(id : String)
let userDic : [String : AnyObject] = ["id":id as AnyObject]
Alamofire.upload(multipartFormData: multipartFormData in
for (key, value) in userDic
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
,to: "http://www.URL.com.au/database/results.php" , method: .post, headers: nil ,
encodingCompletion: encodingResult in
switch encodingResult
case .success(let upload, _, _):
upload.response [weak self] response in
guard self != nil else
return
debugPrint(response)
upload.responseJSON response in
print(response)
// let responseJSON = response.result.value as! NSDictionary
// print(responseJSON)
case .failure(let encodingError):
print("error:\(encodingError)")
)
tableview.reloadData()
override func viewDidAppear(_ animated: Bool)
super.viewDidAppear(animated)
tableview.reloadData()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
//return myarray.count
return arrRes.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell") as! CategoryCellTableViewCell
var dict = arrRes[indexPath.row]
cell.catName.text = dict["category.NAME"] as? String
cell.total?.text = dict["TOTAL"] as? String
return cell
还有我的 CategoryCellTableViewCell.swift 代码:
import UIKit
class CategoryCellTableViewCell: UITableViewCell
@IBOutlet weak var catName: UILabel!
@IBOutlet weak var total: UILabel!
override func awakeFromNib()
super.awakeFromNib()
// Initialization code
override func setSelected(_ selected: Bool, animated: Bool)
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
我试图在网上寻求一些帮助,但无法得到,但非常感谢你的时间:)
字典输出:
SUCCESS: (
NAME = "COSMETIC PRODUCTS & SERVICES";
TOTAL = 1;
id = 54300;
,
NAME = TATTOOING;
TOTAL = 1;
id = 225700;
)
【问题讨论】:
你能显示字典输出吗? 显示使用您的JSON
回复。
@NiravD 我正在使用 Json 响应,但出现错误:线程 1:signal sigabrt
@SarahMalik 为什么你使用arrRes
和tableView
方法而不是类别数组?
【参考方案1】:
试试这个 我认为您忘记了填充数组并设置了数据源和 UITableView 的委托
import UIKit
import Alamofire
import SwiftyJSON
class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate
var tableData = Array<Category>()
var category = [Category]()
var arrRes = [NSDictionary]()
var catTitle = ""
var id = ""
@IBOutlet weak var catTitleRec: UILabel!
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad()
super.viewDidLoad()
catTitleRec.text = catTitle
loadCategories(id:id)
func loadCategories(id : String)
let userDic : [String : AnyObject] = ["id":id as AnyObject]
Alamofire.upload(multipartFormData: multipartFormData in
for (key, value) in userDic
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
,to: "URL" , method: .post, headers: nil ,
encodingCompletion: encodingResult in
switch encodingResult
case .success(let upload, _, _):
upload.response [weak self] response in
guard self != nil else
return
debugPrint(response)
upload.responseJSON response in
print(response)
self.arrRes = response.result.value as? NSArray as! [NSDictionary]
DispatchQueue.main.async
self.tableview.reloadData()
case .failure(let encodingError):
print("error:\(encodingError)")
)
override func viewDidAppear(_ animated: Bool)
super.viewDidAppear(animated)
tableview.reloadData()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
//return myarray.count
return arrRes.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell") as! CategoryCellTableViewCell
var dict = arrRes[indexPath.row]
cell.catName.text = dict["NAME"] as? String
cell.total?.text = dict["TOTAL"] as? String
return cell
【讨论】:
不要只发布代码。解释问题是什么,你的回答如何解决问题。 @JaydeepVyas,我尝试更新块,但仍然没有显示任何结果 @SarahMalik 首先检查您的数组是否填充正确 @JaydeepVyas,好吧,我可以在面板中看到输出 你在调试模式下的填充数组检查是 Array此方法的异步调用,因此您需要在块内重新加载数据,如下所示:
switch encodingResult
case .success(let upload, _, _):
upload.response [weak self] response in
guard self != nil else
return
debugPrint(response)
upload.responseJSON response in
print(response)
// let responseJSON = response.result.value as! NSDictionary
arrRes = responseJSON // you need to assign data here
tableview.reloadData()
// print(responseJSON)
case .failure(let encodingError):
print("error:\(encodingError)")
【讨论】:
【参考方案3】:试试这个。
case .success(let upload, _, _):
upload.response [weak self] response in
guard self != nil else
return
debugPrint(response)
upload.responseJSON response in
print(response)
// let responseJSON = response.result.value as! NSDictionary
// print(responseJSON)
DispatchQueue.main.async
self.tableview.reloadData()
【讨论】:
我尝试使用您的建议,但我无法在 tableview 上加载数据。 Tho,我可以在面板中看到输出【参考方案4】:您在 JSON 中获得多个名称值,它是字典数组,您需要将名称存储在字典中,而不是直接在数组输出中获取,如下所示
for dict in dataDict
let userName = dict["NAME"] as? String
let userTotal = dict["TOTAL"] as? String
// Store data in User Default // Not required
UserDefaults.standard.set(userName, forKey:"username")
UserDefaults.standard.set(userTotal, forKey:"totalNumber")
或将其添加到数组中,在 cellforRow 中使用数组显示详细信息
【讨论】:
以上是关于Swift 3 / Alamofire:无法用数据加载表格的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire 4、Swift 3:无法返回 StatusCode