如何在单个tableview上做api数据json.file数据

时间:2018-09-28 04:25:15

标签: ios

我有如下所示的api。

{"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"}]}

这是我的api格式,因此我使用tableview编写了以下代码。

    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()

}

这是代码。我得到了输出。但是我需要其他的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"]

              }
              ]


}

在NH_QuestionViewModel视图模型中:-

 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)

            }

        }}

在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


    }

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)

            }

在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 {}
        }

    }

因此,如何组合两个数据源。在tableview的noofsection中应该编写什么代码?

所以这些数据也需要进入该表视图中。该怎么办?

这意味着在tableview中首先列出api中的数据,然后再列出Json.file中的数据。如何实现?

1 个答案:

答案 0 :(得分:0)

为了使事情变得简单,您不需要申请独立的  类充当viewModel。最好将一个viewModel用于一个tableView。 一种方法是像下面这样扩展当前的webloadingModel:

c("foo", "bar")

我不知道实现细节,为什么需要datasection2。但是,如果需要,可以使用类变量。然后,您只需在您的viewLoad中插入du​​mmyViewModel方法,而无需更改其他任何内容。如果您需要添加更多功能,请从此处添加。尽量避免使逻辑过于复杂。

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

}

}