Я новичок в 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)
}
}
Заранее большое спасибо!!! Диан.