ios - 从服务器获取数据后,直到单击屏幕后, TableView 才会显示数据

标签 ios json swift uitableview

屏幕不显示数据,直到我点击屏幕或让它等待很长时间 这是我的代码

enter code here

BookMarkVC 类:

UIViewController,UITableViewDataSource,UITableViewDelegate {



    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var menuButton: UIBarButtonItem!


 var bookmarks = [DatumForBookMarksMoel]()

    override func viewWillAppear(_ animated: Bool) {
        getAllBookMarks { (succsees) in
            if succsees
            {
                print ("get all book marks ")
                self.tableView.reloadData()

            }
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()


        menuButton.target  = self.revealViewController()
        menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
        tableView.tableFooterView = UIView()
        // Do any additional setup after loading the view.
        tableView.reloadData()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bookmarks.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "bookMarkCell", for: indexPath) as? BookMarkTabelCell else { return UITableViewCell() }
        cell.priceOfItem.text = "\((bookmarks[indexPath.row].offerPrice) ?? 0)"
        cell.depositValue.text = "\(bookmarks[indexPath.row].insuranceValue ?? 0)"
        cell.nameOfItem.text = "\(bookmarks[indexPath.row].name ?? " ")"
        cell.quantity.text = "\(bookmarks[indexPath.row].quantity ?? 0)"
        cell.metookeyerName.text = "\(bookmarks[indexPath.row].accName ?? " ")"
        cell.orderDate.text = "\(bookmarks[indexPath.row].createdAt ?? " ")"



        return cell

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return CGFloat(300)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    func getAllBookMarks(completion: @escaping CompletionHandler) {
        let body1: [String: Any] = [
            "draw": 3,
            "length": 100,
            "start": 0
        ]
        print ("get item by category mmmmmmmmm")
    //print("\(URL_ADD_BOOK_MARK)\(itemId)")
      print (AuthService.instance.authToken)
        print(HeaderForLoggedUser)
        Alamofire.request(URL_ALL_BOOK_MARK, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: HeaderForLoggedUser).responseJSON { (response) in
            if response.result.error == nil {
                completion(true)
                // print("login Connection done succes and response data back")
                let data = response.data
                do {
                    completion(true)
                    let result = try JSONDecoder().decode(BookMarksModel.self, from: data!)

                    self.bookmarks = (result.data?.data!)!

             /*       DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }*/
                    DispatchQueue.main.async
                        {
                            self.tableView.reloadData()
                    }


                } catch {
                    completion(false)
                    print(error)
                }
            }
            else {
                completion(false)
                debugPrint(response.result.error as Any)
            }
        }




    }

}
class BookMarkTabelCell : UITableViewCell
{


    @IBOutlet weak var meTooKeyNumber: UILabel!

    @IBOutlet weak var metookeyerName: UILabel!
    @IBOutlet weak var orderDate: UILabel!
    @IBOutlet weak var quantity: UILabel!
    @IBOutlet weak var depositValue: UILabel!
    @IBOutlet weak var nameOfItem: UILabel!

    @IBOutlet weak var priceOfItem: UILabel!


} }

我多次使用reload data()来尝试处理这个问题但不起作用

最佳答案

请尝试这个方法:

func getAllBookMarks(completion: @escaping CompletionHandler) {
    let body1: [String: Any] = [
        "draw": 3,
        "length": 100,
        "start": 0
    ]
    print ("get item by category mmmmmmmmm")
//print("\(URL_ADD_BOOK_MARK)\(itemId)")
  print (AuthService.instance.authToken)
    print(HeaderForLoggedUser)
    Alamofire.request(URL_ALL_BOOK_MARK, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: HeaderForLoggedUser).responseJSON { (response) in
        if response.result.error == nil {

            // print("login Connection done succes and response data back")
            let data = response.data
            do {

                let result = try JSONDecoder().decode(BookMarksModel.self, from: data!)

                self.bookmarks = (result.data?.data!)!

                completion(true)



            } catch {
                completion(false)
                print(error)
            }
        }
        else {
            completion(false)
            debugPrint(response.result.error as Any)
        }
    }




}

}

也许对你有帮助。谢谢。

关于ios - 从服务器获取数据后,直到单击屏幕后, TableView 才会显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54211936/

相关文章:

ios - 在 Xcode 中,您将如何拥有只有在用户在应用程序中执行特定操作时才能访问的 View Controller ?

ios - swift : AppDelegate and NSManagedObjectContext are nil

ios - 对协议(protocol)感到困惑

json - bool 值在逻辑应用程序条件下不起作用

ios - 为什么 'nextDateAfterDate' 函数没有按预期工作?

ios - 从 Swift 函数中的异步调用返回数据

swift - 从现有 DispatchQueue 创建 SerialDispatchQueueScheduler 时,internalSerialQueueName 的正确用法是什么

ios - ReactiveCocoa rac_valuesForKeyPath 在 Swift 中不起作用

javascript - 如何从 json 对象输出一些东西?

java - 如何正确从 url 读取 JSON 数组数据