取上的UITableView从JSON数据和显示 [英] Fetching data from JSON and display on UITableView
问题描述
我在网上获取JSON数据并将其转换为NSArray的,并为String和级阵列来管理数据。但是,对于某些原因,code行让任务= session.dataTaskWithRequest(请求,completionHandler后退出
的GetData()
方法: {(数据,回应,误差)
我也证实没有与获取数据没有问题,但它只是不能在表中显示。
我附上我的项目文件也为下载一>
codeS由ViewController.swift
进口的UIKit一流的ViewController:UIViewController的,UITableViewDataSource {
VAR NAMELIST = [NameManager]() @IBOutlet弱VAR NameTable:UITableView的! 覆盖FUNC viewDidLoad中(){
super.viewDidLoad()
的GetData()
//装载视图,通常从笔尖后做任何额外的设置。
NameTable.dataSource =自
NameTable.reloadData()
} 覆盖FUNC didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
可以重新创建任何资源的处置//。
} FUNC的GetData(){
让会话= NSURLSession.sharedSession()
让请求= NSMutableURLRequest(网址:NSURL(字符串:http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2)!)
request.HTTPMethod =GET 让任务= session.dataTaskWithRequest(请求,completionHandler:{(数据,回应,误差) 如果让错误= {错误
打印(错误)
}
如果让数据= {数据
做{
让resultJSON =尝试NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions())
让resultArray = resultJSON作为? NSArray的
在resultArray jsonObjectString!{
让code = jsonObjectString [code作为!串
让名= jsonObjectString [名称]作为!串
让我们描述= jsonObjectString [说明]作为!串
self.nameList.append(NameManager(code:code,名称:名称,描述:描述))
}
self.nameList.count }赶上_ {
打印(收到未格式良好的JSON)
} }
如果让响应= {响应
让HTT presponse =响应作为! NSHTTPURLResponse
打印(响应code = \\(HTT presponse.status code))
} })
task.resume() } FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - GT; INT {
让数= nameList.count
返回计数
} FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath) - GT; {的UITableViewCell
让了myCell = NameTable.dequeueReusableCellWithIdentifier(了myCell,forIndexPath:indexPath)作为一个UITableViewCell myCell.textLabel?的.text =名称列表[indexPath.row]。名称
myCell.detailTextLabel?的.text =名称列表[indexPath.row] .DESCRIPTION 返回了myCell
}}
codeS由NameManager.swift
进口基金会
类NameManager { 变量code:字符串
变数名称:字符串
Var描述:字符串 的init(code:字符串名称:字符串描述:字符串){
自我。code = code
self.name =名称
self.description =说明
}
}
session.dataTaskWithRequest是异步的,在后台线程中自动执行。
当它看到 task.resume()
并开始在后台执行dataTaskWithRequest开始。
所以,你的程序不等待其完成,并开始执行它后面的指令。在你的榜样,您的code将开始执行
NameTable.dataSource =自
NameTable.reloadData()
这是以下getData()方法。一旦后台执行完毕,code你在完成处理程序被执行。所以你的tableView没有刷新。
有不同的方法可以解决这个问题。
一种方法是包括 NameTable.reloadData()
在你完成处理。另一种方式是在完成后台执行从Segue公司的ViewController
希望它帮助。
编辑:
进口的UIKit一流的ViewController:UIViewController的,UITableViewDataSource {
VAR NAMELIST = [NameManager]() @IBOutlet弱VAR NameTable:UITableView的! 覆盖FUNC viewDidLoad中(){
super.viewDidLoad()
NameTable.dataSource =自
的GetData()
//装载视图,通常从笔尖后做任何额外的设置。 //NameTable.reloadData()
} 覆盖FUNC didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
可以重新创建任何资源的处置//。
} FUNC的GetData(){
让会话= NSURLSession.sharedSession()
让请求= NSMutableURLRequest(网址:NSURL(字符串:http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2)!)
request.HTTPMethod =GET 让任务= session.dataTaskWithRequest(请求,completionHandler:{(数据,回应,误差) 如果让错误= {错误
打印(错误)
}
如果让数据= {数据
做{
让resultJSON =尝试NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions())
让resultArray = resultJSON作为? NSArray的
在resultArray jsonObjectString!{
让code = jsonObjectString [code作为!串
让名= jsonObjectString [名称]作为!串
让我们描述= jsonObjectString [说明]作为!串
self.nameList.append(NameManager(code:code,名称:名称,描述:描述))
}
self.nameList.count
dispatch_async(dispatch_get_main_queue(),{
self.NameTable.reloadData()
})
}赶上_ {
打印(收到未格式良好的JSON)
} }
如果让响应= {响应
让HTT presponse =响应作为! NSHTTPURLResponse
打印(响应code = \\(HTT presponse.status code))
} })
task.resume() } FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - GT; INT {
让数= nameList.count
返回计数
} FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath) - GT; {的UITableViewCell
让了myCell = NameTable.dequeueReusableCellWithIdentifier(了myCell,forIndexPath:indexPath)作为一个UITableViewCell myCell.textLabel?的.text =名称列表[indexPath.row]。名称
myCell.detailTextLabel?的.text =名称列表[indexPath.row] .DESCRIPTION 返回了myCell
}}
I'm fetching JSON data online and converting them to NSArray, and to String and class Arrays to manage the data. However, for some reason, the code exits the GetData()
method after the line let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
I've also verified that there was no issues with fetching the data, but it just can't be displayed on the table.
I've attached my project file also for download.
Codes from ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var nameList = [NameManager]()
@IBOutlet weak var NameTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
GetData()
// Do any additional setup after loading the view, typically from a nib.
NameTable.dataSource = self
NameTable.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func GetData(){
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2")!)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let resultArray = resultJSON as? NSArray
for jsonObjectString in resultArray!{
let code = jsonObjectString["code"] as! String
let name = jsonObjectString["name"] as! String
let description = jsonObjectString["description"] as! String
self.nameList.append(NameManager(code: code, name: name, description: description))
}
self.nameList.count
}catch _{
print("Received not-well-formatted JSON")
}
}
if let response = response {
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
let count = nameList.count
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let myCell = NameTable.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
myCell.textLabel?.text = nameList[indexPath.row].name
myCell.detailTextLabel?.text = nameList[indexPath.row].description
return myCell
}
}
Codes from NameManager.swift
import Foundation
class NameManager{
var code:String
var name:String
var description:String
init(code: String, name: String, description: String){
self.code = code
self.name = name
self.description = description
}
}
session.dataTaskWithRequest is asynchronous and is automatically executed in background thread.
The dataTaskWithRequest is started when it sees the task.resume()
and starts executing in background.
So, your program does not wait for its completion and starts to execute the instructions following it. In your example, your code will start to execute
NameTable.dataSource = self
NameTable.reloadData()
which are following GetData() method. Once the background execution is completed, the code you have in the completion handler is executed. So your tableView is not refreshed.
There are different ways you can approach this issue.
one way is to include NameTable.reloadData()
in your completion handler. Another way is to segue from a ViewController when background execution is completed.
Hope it helps.
EDIT:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var nameList = [NameManager]()
@IBOutlet weak var NameTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
NameTable.dataSource = self
GetData()
// Do any additional setup after loading the view, typically from a nib.
//NameTable.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func GetData(){
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2")!)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let resultArray = resultJSON as? NSArray
for jsonObjectString in resultArray!{
let code = jsonObjectString["code"] as! String
let name = jsonObjectString["name"] as! String
let description = jsonObjectString["description"] as! String
self.nameList.append(NameManager(code: code, name: name, description: description))
}
self.nameList.count
dispatch_async(dispatch_get_main_queue(), {
self.NameTable.reloadData()
})
}catch _{
print("Received not-well-formatted JSON")
}
}
if let response = response {
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
let count = nameList.count
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let myCell = NameTable.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
myCell.textLabel?.text = nameList[indexPath.row].name
myCell.detailTextLabel?.text = nameList[indexPath.row].description
return myCell
}
}
这篇关于取上的UITableView从JSON数据和显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!