简体   繁体   中英

UITableView doesn't refresh on iOS

My pull to refresh feature actually work, but doesn't reload the data. If I close and open the app I can reach the data, but I couldn't load the data if I use pull to refresh.

var page : Int = 1
var refresher: UIRefreshControl!
override func viewDidLoad() {
        super.viewDidLoad()


        refresher = UIRefreshControl()

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

        refresher.addTarget(self, action: #selector(newPollsTableViewController.refresh), forControlEvents: UIControlEvents.ValueChanged)

        self.tableView.addSubview(refresher)

            data_request() 
}

this is my data_request() func:

func data_request(){
    let user_id = Data[0].valueForKey("user_id") as? String!

    let url:NSURL = NSURL(string: "http://..../perspective/\(user_id!)/page/"+"\(page)" )!

    let session = NSURLSession.sharedSession()
    self.page = self.page + 1


    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "GET"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData


    let task = session.dataTaskWithRequest(request) {
        (let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        var json: AnyObject?

        do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
        } 
        catch {
            return
        }

        guard let data_array = json as? NSArray else {
            return
        }

        for i in 0..<data_array.count
        {
            if let add = data_array[i] as? NSDictionary
            {   
                self.obj.append(Obj(data:add))
            }
        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in   
            self.tableView.reloadData()
        })
     }
    task.resume()  
}

and I call the my refresh func when I pull the refresh the table.

func refresh() {
        self.page = 1
        data_request()
        self.refresher.endRefreshing()
}

each time I pull the refresh the table it enters the data_request() func but it doesn't update the table.

data_request()
self.refresher.endRefreshing()

data_request is asynchronous method and it returns almost immediately. So you end refreshing before data is actually loaded.

What you should probably do is to move endRefreshing call into data task completion closure. Make sure you call it on main queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM