Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

ios - How to do api data json.file data on the single tableview

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To make things easier, You don't need to apply an independent class to behave as a viewModel. It's better to use one viewModel for one tableView. One way is to extend your current webloadingModel like the following :

protocol NHDummyViewModel {
 static  var datasection2 : [String:Any]? {get set}
 func loadFromDummyData(completion :@escaping (NH_DummyDataSourceModel?) -> ())
}

extension NH_QuestionViewModel : NHDummyViewModel{

 static var datasection2 : [String:Any]?


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

                NH_QuestionViewModel.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 {}
    }

}

}

I don't know the implementation details, why do you need datasection2. But if you need it you can use class variable. Then you just insert the dummyViewModel method in your viewLoad and don't not need to change anything else. If you need to add more functions, add from here. Try to avoid to make logics too complicated.

 override func viewDidLoad() {
    super.viewDidLoad()


    questionViewModel.loadData { (isSuccess) in




        if(isSuccess == true)
        {

            self.questionViewModel.loadFromDummyData(completion: { (NH_DummyDataSourceModel) in




            let sec = self.questionViewModel.numberOfSections()
            for _ in 0..<sec
            {


                self.questionViewModel.answers1.append("")
                self.questionViewModel.questions1.append("")
                self.questionViewModel.questionlist1.append("")


            }
            //questionViewModel.numberOfSections()


            self.activityindicator.stopAnimating()
            self.activityindicator.isHidden = true
            self.tableview.refreshControl = self.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: UIAlertAction.Style.default) {
                UIAlertAction in
                NSLog("OK Pressed")


                self.viewDidLoad()


            }
            controller.addAction(okAction)


            self.present(controller, animated: true, completion: nil)

        }

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}
}



enter code here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...