【问题标题】:Pull To Refresh Not Refreshing JSON Data拉取刷新不刷新 JSON 数据
【发布时间】:2016-05-07 02:05:46
【问题描述】:

我一直在尝试对我的 tableview 实施 Pull to Refresh 以刷新来自服务器的 JSON 数据。在我在调试区域屏幕上尝试过的内容中,它显示数据重新加载,但是当我对服务器上的 PHP 文件进行更改时,单元格标签和图像不会刷新......我正在使用以下代码:

    import UIKit

    class JSONData: UITableViewController {    

    var newsList = [News]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.loadJSONDATA()

    }


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

// MARK: - Table source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.

    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return newsList.count


}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! NewsStrings

    let s = newsList[indexPath.row] as News

    cell.labellName.text = s.newsName
    cell.labelDesc.text = s.newsDesc
    cell.labelDate.text = s.newsDate
    cell.imgvImage.image = UIImage(named: "BgIcon.jpg")

    if let img = UIImage(data: s.newsImage)
    {
        cell.imgvImage.image = img
    }else
    {
        self.loadImages(s, indexPath: indexPath)
    }



    return cell

}


///////////////// JSON DATA ////////////////////////


func loadJSONDATA()
{ 
    let urlString = "http://example.com/folder/JSON.php"

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)

    if let url = NSURL(string: urlString)
    {

      let request = NSURLRequest(URL: url)

        let taskData = session.dataTaskWithRequest(request, completionHandler: {

            (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in


            if (data != nil)
            {

                var parseError:NSError?
                let parsedNews = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! NSDictionary

                //print("JSON Data \n \(parsedNews)")

                if let news:AnyObject = parsedNews["News"]
                {
                    self.parseJSON(news)
                }


            } else

            {



            }

        })

        taskData.resume()


    }

}



/////////// LODING JSON DATA //////////////

func parseJSON(jsonData:AnyObject)
{

    if let newsData = jsonData as? [[NSObject:AnyObject]]
    {

        var news:News


        for s in newsData {

            news = News()


            if let sId:AnyObject = s["NewsID"]
            {

                if let NewsID = sId as? String

                {
                    print("News id = \(NewsID)")

                }

            }


            if let sn:AnyObject = s["newsName"]
            {

                if let newsName = sn as? String

                {

                    news.newsName = newsName
                    //println("Store id = \(storeName)")

                }

            }

            if let sn:AnyObject = s["newsDate"]
            {

                if let newsDate = sn as? String

                {

                    news.newsDate = newsDate
                    //println("Store id = \(storeName)")

                }

            }


            if let sn:AnyObject = s["newsIcon"]
            {

                if let newsIcon = sn as? String

                {

                    news.newsImageName = newsIcon
                    //println("News Icon = \(newsIcon)")

                }

            }


            if let sn:AnyObject = s["newsDesc"]
            {

                if let newsIcon = sn as? String

                {

                    news.newsDesc = newsIcon

                }

            }


         newsList += [news]


        }


        NSOperationQueue.mainQueue().addOperationWithBlock(){

            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            self.tableView.reloadData()
        }    
    }  
}


/////////// LODING IMAGES FROM JSON DATA //////////////

func loadImages(news:News, indexPath:NSIndexPath)
{

    let urlString = news.newsImageName


    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config, delegate:nil, delegateQueue: nil)


    if let url = NSURL(string: urlString)
    { 
        let request = NSURLRequest(URL: url)

        let taskData = session.dataTaskWithRequest(request, completionHandler: {

            (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in


            if (data != nil)
            {

                news.newsImage = data!
                let image = UIImage(data: data!)

                dispatch_async(dispatch_get_main_queue(),{

                    if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? NewsStrings {
                        cell.imgvImage.image = image
                    }
                })



            } else

            {


            }

        })

        taskData.resume()   
    }   
    }  

    }

【问题讨论】:

    标签: php json swift xcode7


    【解决方案1】:

    您可以像下面的代码一样在表格视图中添加拉动刷新,

    var refreshControl = UIRefreshControl()
    

    在视图中确实加载了,

    self.refreshControl.addTarget(self, action: Selector("loadJSONDATA"), forControlEvents: UIControlEvents.ValueChanged)
    self.addSubview(self.refreshControl) // OR self.myTable?.addSubview(self.refreshControl)
    

    然后在self.parseJSON(news)后面加上这一行

    self.refreshControl.endRefreshing()
    

    这将为您提供充分的帮助。 :)

    【讨论】:

    • 我已经尝试过了,但是当我在服务器上添加或更改 PHP 文件时,表格单元格标签和图像仍然不会刷新
    • 你用断点检查了吗?检查编译器是否通过某些行,例如重新加载表视图等
    【解决方案2】:

    我有一些东西让它工作,这就是我的 viewDidLoad:

     self.refreshControl?.addTarget(self, action: #selector(NewsList.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
    

    handleRefresh 的函数:

    func handleRefresh(refreshControl: UIRefreshControl) {
    
    newsList.removeAll() //<-This clear the whole tableview(labels, images,ect...)making table view blank
    
    if self.refreshControl!.refreshing
    {
        self.loadRecords()  //<-Reloads All data & labels
        self.refreshControl!.endRefreshing()
    }
     }
    

    唯一的问题是应用程序在执行“拉刷新”倍数后崩溃

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多