我写了这段代码来从这个JSON文件中读取表格视图中的国家:
JSON:
[5]
0: {
"country": "Afghanistan"
"code": "AF"
}-
1: {
"country": "Åland Islands"
"code": "AX"
}-
2: {
"country": "Albania"
"code": "AL"
}-
3: {
"country": "Algeria"
"code": "DZ"
}-
4: {
"country": "American Samoa"
"code": "AS"
}
我的代码:
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tableCountryView: UITableView!
var json_url = "........ my url here ......... "
var TableData:Array< datastruct > = Array < datastruct >()
enum ErrorHandler:ErrorType
{
case ErrorFetchingResults
}
struct datastruct
{
var country_name:String?
var country_code:String?
init(add: NSDictionary)
{
country_name = add["country"] as? String
country_code = add["code"] as? String
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableCountryView.dataSource = self
tableCountryView.delegate = self
get_data_from_url(json_url)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let data = TableData[indexPath.row]
cell.textLabel?.text = data.country_name! + " - " + data.country_code!
return cell
}
func get_data_from_url(url:String)
{
let url:NSURL = NSURL(string: url)!
let session = NSURLSession.sharedSession()
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
}
dispatch_async(dispatch_get_main_queue(), {
self.extract_json(data!)
return
})
}
task.resume()
}
func extract_json(jsonData:NSData)
{
let json: AnyObject?
do {
json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
} catch {
json = nil
return
}
if let list = json as? NSArray
{
for (var i = 0; i < list.count ; i++ )
{
if let data_block = list[i] as? NSDictionary
{
TableData.append(datastruct(add: data_block))
}
}
do_table_refresh()
}
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableCountryView.reloadData()
return
})
}
}
此代码适用于第一个JSON语法,但如果我想读取子数组,如下面JSON文件中的语法,我可以在之前的代码中编辑它。
JSON:
{
"Countries": [4]
0: {
"countryname": "Egypt"
"code": "20"
}-
1: {
"countryname": "India"
"code": "91"
}-
2: {
"countryname": "United States"
"code": "1"
}-
3: {
"countryname": "Turkey"
"code": "90"
}-
}
此外,我在故事板上有按钮,我想在点击此按钮时显示国家的表格视图然后选择一个国家并关闭此表并在按钮上显示结果,我知道这很容易但我开始仅在2周内学习IOS,我希望你能在这些案例中给我建议。