无法通过拉取刷新我的 JSON 数据以在 tableview 控制器中刷新

Posted

技术标签:

【中文标题】无法通过拉取刷新我的 JSON 数据以在 tableview 控制器中刷新【英文标题】:Not able to refresh my JSON data through pull to refresh in tableview controller 【发布时间】:2017-06-23 05:51:20 【问题描述】:

我在通过拉刷新刷新我的 JSON 数据时遇到问题。当我启动我的应用程序时,它正在显示数据,但是当我拉刷新时它没有刷新。 我已经实现了Refresh Control 来刷新数据。我可以看到下拉刷新的***图标,但它没有更新 JSON 数据。

这是我的代码:

struct JSONData 
    let country: String
    let indicename: String
    let currPrice: String
    let chg: String
    let perChg: String

    init?(dictionary: [String:Any]) 
        guard let country = dictionary["Country"] as? String,
            let indicename = dictionary["Indicename"] as? String,
            let currPrice = dictionary["CurrPrice"] as? String,
            let chg = dictionary["Chg"] as? String,
            let perChg = dictionary["perChg"] as? String else 
                return nil
        
        self.country = country
        self.indicename = indicename
        self.currPrice = currPrice
        self.chg = chg
        self.perChg = perChg
    


       class SouthAViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,IndicatorInfoProvider 

    var datas = [JSONData]()
        var refreshControl = UIRefreshControl()

          @IBOutlet var tableview: UITableView!

        var arrowupimage : UIImage = UIImage(named : "arrowup")!
        var arrowdownimage : UIImage = UIImage(named : "arrowdown")!

        // I haven't shared the URL of parsing for security reasons

        let url=NSURL(string:"*******************************")
        let stringurl = "***************************"



        override func viewDidLoad() 
            super.viewDidLoad()

            if #available(ios 10.0, *) 
                tableview.refreshControl = refreshControl
             else 
                tableview.addSubview(refreshControl)
            

            self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")

            self.refreshControl.addTarget(self, action: #selector(SouthAViewController.refresh), for: UIControlEvents.valueChanged)


            navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
            self.downloadJsonWithURL()
            tableview.delegate = self
            tableview.dataSource = self
        

        func refresh()
            self.downloadJsonWithURL()

        

        // downloading JSON data to display on this class

        func downloadJsonWithURL() 

             let task = URLSession.shared.dataTask(with: URL(string: stringurl)!)  (data, response, error) in
            if error != nil 
              //  print(error?.localizedDescription)
                return
            
            if let contdata = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:Any] 

                if let arrJSON = contdata["data"] as? [[String:Any]] 
                    self.datas = arrJSON.flatMap(JSONData.init)

                        //Reload tableView and endRefreshing the refresh control
                        DispatchQueue.main.async 
                        self.tableview.reloadData()
                        self.refreshControl.endRefreshing()
                        
                
            
        
        task.resume()

        

        override func didReceiveMemoryWarning() 
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        



        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

            return datas.count
        

        //setting data on the table view cell

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
            let cell = tableView.dequeueReusableCell(withIdentifier: "southacell", for: indexPath) as! southacell


        cell.Indicename?.text = datas[indexPath.row].indicename
        cell.Country?.text = datas[indexPath.row].country
        cell.CurrPrice?.text = datas[indexPath.row].currPrice


            return cell
        

    

json 示例:

  "data":[  
        
         "Country":"China",
         "Indicename":"SZSE COMPONENT INDEX",
         "date":"2017-06-23 14:53:57",
         "zone":"GMT+8",
         "CurrPrice":"10355.3",
         "Chg":"90.07",
         "PerChg":"0.88",
         "prev_close":"10265.2"
      ,
        
         "Country":"China",
         "Indicename":"Shanghai Composite",
         "date":"2017-06-23 14:52:54",
         "zone":"GMT+8",
         "CurrPrice":"3155.9",
         "Chg":"8.44",
         "PerChg":"0.27",
         "prev_close":"3147.45"
      
]

【问题讨论】:

刷新时从服务器返回数据 @SamarthKejriwal 问题很小,将 JSONData let perChg = dictionary["PerChg"] as? String else init 中的单行更改为键 PerChg P 是大写,目前它是小写的,让它大写,你们都很好去。 @SamarthKejriwal 刷新 tableView 时是否显示刷新控件?还要在refresh 中放置断点并检查它是否被调用? @NiravD Okk 先生! @NiravD 好的先生。一世 。将把链接发给你。请你有空的时候看看 【参考方案1】:

不要使用Data(contentsOf:)URL检索数据你需要使用URLSessiondatataskURL检索数据之后你需要重新加载tableView和结束动画RefreshControl 的完成块内的 datatask(with:)。此外,您需要做的不是处理多个数组,而是创建一个自定义数组 classstruct

struct Data 
    var country: String
    var indicename: String
    var currPrice: String
    var chg: String
    var perChg: String

    init?(dictionary: [String:Any]) 
        guard let country = dictionary["Country"] as? String,
              let indicename = dictionary["Indicename"] as? String,
              let currPrice = dictionary["CurrPrice"] as? String,
              let chg = dictionary["Chg"] as? String,
              let perChg = dictionary["PerChg"] as? String else 
            return nil
        
        self.country = country
        self.indicename = indicename
        self.currPrice = currPrice
        self.chg = chg
        self.perChg = perChg
    

现在只声明一个[Data] 类型的数组,并在您的tableView 方法中使用它。

var datas = [Data]()

现在只需使用这个单一数组来存储所有数据并在tableView 中显示数据。

func refresh()
    self.downloadJsonWithURL()


func downloadJsonWithURL() 
    let task = URLSession.shared.dataTask(with: url)  (data, response, error) in
        if error != nil 
            print(error?.localizedDescription)
            return
        
        if let contdata = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:Any] 
            if let arrJSON = contdata["data"] as? [[String:Any]] 
                self.datas = arrJSON.flatMap(Data.init)
                //Reload tableView and endRefreshing the refresh control 
                DispatchQueue.main.async 
                    self.tableView.reloadData()
                    self.refreshControl.endRefreshing()
                
            
        
    
    task.resume()


//tableView methods

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

    return data.count


//setting data on the table view cell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: "southacell", for: indexPath) as! southacell


    let curpricefloat : Double = Double(datas[indexPath.row].currPrice)!
    let Chgfloat : Double = Double(datas[indexPath.row].chg)!
    let perchgfloat : Double = Double(datas[indexPath.row].perChg)!

    cell.Indicename?.text = datas[indexPath.row].indicename
    cell.Indicename.font = UIFont.boldSystemFont(ofSize: 19.0)
    cell.Country?.text = datas[indexPath.row].country

    cell.PerChg?.text = "(" + String(format: "%.2f", perchgfloat) + "%)"
    cell.CurrPrice?.text = String(format: "%.2f", curpricefloat)
    cell.Chg?.text = String(format: "%.2f", Chgfloat)

    if Float((cell.Chg?.text)!)! < 0 

        datas[indexPath.row].chg = datas[indexPath.row].chg.replacingOccurrences(of: "-", with: "")
        datas[indexPath.row].perChg = datas[indexPath.row].perChg.replacingOccurrences(of: "-", with: "")

        cell.PerChg?.text = "(" + datas[indexPath.row].perChg + "%)"
        cell.Chg?.text = datas[indexPath.row].chg

        cell.Chg?.textColor = UIColor.red
        cell.PerChg?.textColor = UIColor.red
        cell.arrow?.image = UIImage(named : "arrowdown")

     else
    
        cell.Chg?.textColor = UIColor.green
        cell.PerChg?.textColor = UIColor.green
        cell.arrow?.image = UIImage(named : "arrowup")
    

    if cell.Country!.text! == "Argentina"
        cell.countryFlag?.image = UIImage(named : "argentina")
    
    else if cell.Country!.text! == "Brazil"
        cell.countryFlag?.image = UIImage(named : "brazil")
    
    else if cell.Country!.text! == "Peru"
        cell.countryFlag?.image = UIImage(named : "peru")
    
    else
        cell.countryFlag?.image = UIImage(named : "unknown")
    

    return cell

【讨论】:

@SamarthKejriwal 尝试编辑后的答案并创建一些结构或类 它仍然无法正常工作,先生。不刷新数据 需要有关 ios 部署版本的帮助 我想要一些关于 ios 中滚动视图的帮助 @SamarthKejriwal 请将其添加为一个新问题,如果我有解决方案,请给我发送链接【参考方案2】:

尝试以下方法:

override func viewDidLoad() 
    super.viewDidLoad()

    // MARK: Refresh control
    updateData.backgroundColor = .black
    updateData.tintColor = .white
    updateData.attributedTitle = NSAttributedString(string: "Updating Tap 
List...", attributes: [NSForegroundColorAttributeName: UIColor(red: 
255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)])
    updateData.addTarget(self, action: 
#selector(ViewController.loadNewData), for: UIControlEvents.valueChanged)
    tapListTableView.addSubview(updateData)
    tapListTableView.sendSubview(toBack: updateData)

        DispatchQueue.main.async 
            self.tableview.reloadData()
        
    

【讨论】:

以上是关于无法通过拉取刷新我的 JSON 数据以在 tableview 控制器中刷新的主要内容,如果未能解决你的问题,请参考以下文章

无法加载 JSON 数据以在 ListView 中显示

无法移除拉取刷新列表视图的焦点

读取 txt 文件 JSON 数据以在 Cloud Pub Sub 中发布消息

下拉以在 swift UI 中刷新数据

使用 Swift 3 拉动刷新和 Alamofire

无法取消嵌套 json 文件以在 r 中创建地图?