Swift2刷新table查看内容
Swift 2 refresh table view contents
我写了一个 "refresh" 方法,它应该在 table 视图中显示新项目,但它似乎没有正确地重新加载单元格。
func refresh(sender:AnyObject) {
page = 1
self.data_request()
}
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()
}
它不更新单元格。
它就这样卡住了,没有加载数据
应用以下代码重新加载table视图,希望对您有所帮助。
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.tableView.reloadData()
})
或
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
我写了一个 "refresh" 方法,它应该在 table 视图中显示新项目,但它似乎没有正确地重新加载单元格。
func refresh(sender:AnyObject) {
page = 1
self.data_request()
}
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()
}
它不更新单元格。
它就这样卡住了,没有加载数据
应用以下代码重新加载table视图,希望对您有所帮助。
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.tableView.reloadData()
})
或
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})