拉动以刷新不刷新JSON数据

时间:2016-05-07 02:05:47

标签: php json swift xcode7

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

    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()   
    }   
    }  

    }

2 个答案:

答案 0 :(得分:0)

您可以在表格视图中添加pull to refresh,如下面的代码

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(新闻)

之后添加此行
self.refreshControl.endRefreshing()

这将对您有所帮助。 :)

答案 1 :(得分:0)

我有一些东西让它工作,这就是我在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()
}
 }

唯一的事情就是应用程序在执行&#34; Pull to refresh&#34;之后崩溃了。倍数

相关问题