【发布时间】:2017-10-11 04:01:24
【问题描述】:
我是 Xcode 和 Swift 的新手。我需要帮助将 JSON 文件中的数据显示到带有部分和行的 TableView 中。我需要在每个街区展示不同的餐厅。我想我需要在我的 JSON 文件中进行更改,但我无法弄清楚。我真的很感激任何帮助。干杯。
这是我的 JSON 文件:
{
"hoods": {
"neighborhoodNames": {
"marina":[
{
"name": "MARINA-1",
"dob": "December 18, 1963",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
},
{
"name": "MARINA-2",
"description": "Tom Cruise, is an American film actor and producer. He has been nominated for three Academy Awards and has won three Golden Globe Awards. He started his career at age 19 in the 1981 film Endless Love.",
"dob": "July 3, 1962",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg"
},
{
"name": "MARINA-3",
"description": "John Christopher 'Johnny' Depp II is an American actor, film producer, and musician. He has won the Golden Globe Award and Screen Actors Guild award for Best Actor.",
"dob": "June 9, 1963",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg"
}
],
"MISSION":[
{
"name": "MISSION-1",
"dob": "December 18, 1963",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
},
{
"name": "MISSION-2",
"dob": "July 3, 1962",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg"
},
{
"name": "MISSION-3",
"dob": "June 9, 1963",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg"
},
{
"name": "MISSION-4",
"dob": "June 9, 1963",
"image": "http://microblogging.wingnity.com/JSONParsingTutorial/johnny.jpg"
}
]}
}
}
这是 JSON 文件的链接:http://barhoppersf.com/json/hoods.json
这是我的 Xcode:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let urlString = "http://barhoppersf.com/json/hoods.json"
@IBOutlet weak var tableView: UITableView!
var nameArray:[[String]] = []
var dobArray:[[String]] = []
var imgURLArray:[[String]] = []
var neighborhoodNames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.downloadJsonWithURL()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
if let actorArray = jsonObj!.value(forKey: "hoods") as? NSArray {
for actor in actorArray{
if let actorDict = actor as? NSDictionary {
if let name = actorDict.value(forKey: "neighborhoodNames") {
self.neighborhoodNames.append(name as! String)
}
if let name = actorDict.value(forKey: "name") {
self.nameArray.append([name as! String])
}
if let name = actorDict.value(forKey: "dob") {
self.dobArray.append([name as! String])
}
if let name = actorDict.value(forKey: "image") {
self.imgURLArray.append([name as! String])
}
}
}
}
// self.nameArray = self.nameArray.sorted()
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 15)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData as Any)
}).resume()
}
// MARK: - changing the color, background and position of the header
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.self.init(red: 254/255, green: 170/255, blue: 25/255, alpha: 1.0)
let headerLabel = UILabel(frame: CGRect(x: 8, y: 5, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
headerLabel.font = UIFont(name: "Trebuchet MS", size: 15)
headerLabel.textColor = UIColor.darkGray
headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)
headerLabel.sizeToFit()
headerView.addSubview(headerLabel)
return headerView
}
// MARK: - changing the size of the header cell
// func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// return 40
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (nameArray[section].count)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return neighborhoodNames[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return neighborhoodNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
// cell.nameLabel.text = nameArray[indexPath.row]
cell.nameLabel?.text = nameArray[indexPath.section][indexPath.row]
return cell
}
// set up A_Z index
// func sectionIndexTitles(for tableView: UITableView) -> [String]? {
// return indexName
// }
// call correct section when index is tapped
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
guard let index = indexName.index(of: title) else {
return -1
}
return index
}
///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.imageString = imgURLArray[indexPath.section][indexPath.row]
vc.nameString = nameArray[indexPath.section][indexPath.row]
vc.dobString = dobArray[indexPath.section][indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
提前非常感谢!!! 点。
【问题讨论】:
-
您的问题是什么?你有什么问题?请只发布相关代码。
-
我正在尝试在 TableView 部分的行中显示所有不同的餐厅(Marina-1、Marina-2...)和社区的名称(Marina)。谢谢。
-
上面的JSON怎么和JSON文件的链接不匹配?
-
对不起,伙计们。 JSON 的 url 现在是正确的。谢谢
标签: ios json swift uitableview