I have api as below.
{"data":[{"id":25,"question":"How are u?","options":["fine","Not fine","No"],"button_type":"2","option_count":"4"},{"id":26,"question":"How your name start with 'a' letter?","options":["Yes","No"],"button_type":"2","option_count":"2"}]}
This is my api format ,So i used tableview my code as below.
func numberOfSections(in tableView: UITableView) -> Int {
return questionViewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let identifier = "HeaderCell"
var headercell: NH_questionheader! = tableView.dequeueReusableCell(withIdentifier: identifier) as? NH_questionheader
if headercell == nil {
tableView.register(UINib(nibName: "NH_questionheader", bundle: nil), forCellReuseIdentifier: identifier)
headercell = tableView.dequeueReusableCell(withIdentifier: identifier) as? NH_questionheader
}
headercell.setReviewData(reviews:questionViewModel.titleForHeaderInSection(atsection:section))
return headercell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if tableView == tableview{
return 150
}
return 20
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tableview{
return questionViewModel.numberOfRowsIn(section: section)
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
print(model.answerType)
print(model.answerType?.rawValue)
switch model.answerType {
case .NHAnswerRadioButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NHRadioTypeCell.identifier) as? NHRadioTypeCell {
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath))
cell.delegate = self
return cell
}
case .NHAnswerCheckboxButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NHCheckBoxTypeCell.identifier, for: indexPath) as? NHCheckBoxTypeCell {
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath)) // cell.item = item
return cell
}
case .NHAnswerSmileyButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NHSmileyTypeCell.identifier) as? NHSmileyTypeCell{
cell.textLabel?.text = ""
return cell
}
case .NHAnswerStarRatingButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NHStarRatingTypeCell.identifier) as? NHStarRatingTypeCell {
cell.textLabel?.text = ""
return cell
}
case .NHAnswerTextButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier:NHTextTypeCell.identifier, for: indexPath) as? NHTextTypeCell{
cell.textLabel?.text = ""
return cell
}
default:
return UITableViewCell()
}
return UITableViewCell()
}
This is the code.And i got the output .But how i need have other json.file
{
"data":[
{
"question": "Gender",
"options": ["Male","Female"],
"button_type":"2"
},
{
"question": "How old are you",
"options": ["Under 18","Age 18 to 24","Age 25 to 40","Age 41 to 60","Above 60"],
"button_type":"2"
},
{
"button_type":"2",
"question": "I am filling the Questionnaire for?",
"options": ["Myself","Mychild","Partner","Others"]
}
]
}
In NH_QuestionViewModel viewmodel:-
func loadData(completion :@escaping (_ isSucess:Bool) -> ()){
loadFromWebserviceData { (newDataSourceModel) in
if(newDataSourceModel != nil)
{
self.datasourceModel = newDataSourceModel!
completion(true)
}
else{
completion(false)
}
}
}
func loadFromWebserviceData(completion :@escaping (NH_QuestionDataSourceModel?) -> ()){
//with using Alamofire ..............
// http://localhost/json_data/vendorlist.php
Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON{ response in
let status = response.response?.statusCode
print("STATUS (status)")
print(response)
switch response.result{
case .success(let data):
print("success",data)
let result = response.result
print(result)
if let wholedata = result.value as? [String:Any]{
print(wholedata)
self.datasection1 = wholedata
if let data = wholedata["data"] as? Array<[String:Any]>{
print(data)
print(response)
for question in data {
let typebutton = question["button_type"] as? String
print(typebutton)
self.type = typebutton
let options = question["options"] as! [String]
// self.dataListArray1 = [options]
self.tableArray.append(options)
// self.savedataforoptions(completion: <#T##(NH_OptionslistDataSourceModel?) -> ()#>)
self.no = options.count
}
print(self.tableArray)
let newDataSource:NH_QuestionDataSourceModel = NH_QuestionDataSourceModel(array: data)
completion(newDataSource)
}
}
case .failure(let encodingError ):
print(encodingError)
// if response.response?.statusCode == 404{
print(encodingError.localizedDescription)
completion(nil)
}
}}
In viewcontroller
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, withViewModel viewModel:NH_QuestionViewModel,withDummyDataViewModel DummyDataviewModel:NH_DummyDataViewModel) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
questionViewModel = viewModel
dummyDataViewModel = DummyDataviewModel
}
the viewdidload:-
questionViewModel.loadData { (isSuccess) in
if(isSuccess == true)
{
let sec = self.questionViewModel.numberOfSections()
for _ in 0..<sec
{
self.questionViewModel.answers1.add("")
self.questionViewModel.questions1.add("")
self.questionViewModel.questionlist1.add("")
}
//questionViewModel.numberOfSections()
self.activityindicator.stopAnimating()
self.activityindicator.isHidden = true
self.tableview.refreshControl = refreshControl
self.tableview .allowsMultipleSelection = false
self.tableview.reloadData()
}
else{
self.activityindicator.stopAnimating()
self.activityindicator.isHidden = true
let controller = UIAlertController(title: "No Internet Detected", message: "This app requires an Internet connection", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
self.viewDidLoad()
}
controller.addAction(okAction)
self.present(controller, animated: true, completion: nil)
}
In NHDummyViewModel:-
func loadFromDummyData(completion :@escaping (NH_DummyDataSourceModel?) -> ()){
if let path = Bundle.main.path(forResource: "jsonData", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
do {
let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
self.datasection2 = jsonResult as! [String : Any]
if let people = jsonResult["data"] as? Array<[String:Any]> {
// self.dict = people
for person in people {
let options = person["options"] as! [String]
self.tableArray.append(options)
let name = person ["question"] as! String
self.tableArray.append(options)
}
let newDataSource:NH_DummyDataSourceModel = NH_DummyDataSourceModel(array: people)
completion(newDataSource)
}
} catch {}
} catch {}
}
}
So there how to combine the two dataSource. And what should code in the noofsection in tableview?
So this data also needed to get in that tableview.How to do?
That means In the tableview first list the data from the api ,Then from list the data from the Json.file.How to implement?
See Question&Answers more detail:
os