订单存储为Order
个对象:let orders = [Order]()
我的想法是每秒调用我的API,当创建新单元格时,表格应显示新单元格。
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: "GetOrders", userInfo: nil, repeats: true)
这段代码确实刷新了我的函数以获取数据但重复了单元格!!
所以在GetOrders
函数的开头我擦除了数组,然后用API中的新数组上传它。
func GetOrders (){
orders = []
但是当从数据库中删除新订单时代码会崩溃。它显示在表格中。当我点击它返回'指数超出范围'因为这个功能
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let order = orders[indexPath.row]
guard orders.count > indexPath.row else {
print("Index out of range")
return
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! OrderDetailsController
viewController.passedValue = order.id
self.present(viewController, animated: true , completion: nil)
}
更新
func GetOrders (){
orders = []
print("hi")
let urlStr = "api/orders"
let url = URL(string: urlStr)
let user = "api"
let password = "Apipass"
var headers: HTTPHeaders = [
"Authorization": "Basic YXBpdXNlcjpBcGlBdXRoUGFzczIwMTchQCM="
]
Alamofire.request(url!, method: .get ,encoding: URLEncoding.default, headers: headers).responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
let data = JSON(value)
for (key,subJson):(String, JSON) in data[0] {
//Do something you want
let logo = subJson["family"]["logo"]
let logoString = "img/\(logo)"
if let date = subJson["family"]["updated_at"].string {
print(date)
if let cleintName = subJson["client"]["name"].string {
let info = Order(shopname: shopname, shopaddress: shopaddr, clientName: cleintName, ClientAddress: clientAddres, PerferTime: time, Cost: subtotal , date : time , Logo : logoString ,id : id)
self.orders.append(info)
}
self.tableview.reloadData()
}
}
答案 0 :(得分:0)
您是否尝试过使用主线程?
DispatchQueue.main.async {
self.tableView.reloadData()
}