Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在单个tableview上处理api数据json.file数据_Ios - Fatal编程技术网

Ios 如何在单个tableview上处理api数据json.file数据

Ios 如何在单个tableview上处理api数据json.file数据,ios,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

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

}
这是我的api格式,所以我使用tableview查看我的代码,如下所示

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

              }
              ]


}
在NHU问题视图模型视图模型中:-

 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)

            }

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

            }
questionViewModel.loadData{(isSuccess)位于
如果(isSuccess==true)
{
设sec=self.questionViewModel.numberOfSections()
对于0中的uu…()){
如果let path=Bundle.main.path(forResource:“jsonData”,类型为:“json”){
做{
让jsonData=try NSData(contentsOfFile:path,options:NSData.ReadingOptions.mappedIfSafe)
做{
让jsonResult:NSDictionary=try JSONSerialization.jsonObject(使用:jsonData作为数据,选项:JSONSerialization.ReadingOptions.mutableContainers)作为!NSDictionary
self.datasection2=jsonResult as![String:Any]
如果让people=jsonResult[“数据”]作为数组{
//self.dict=人
为人处事{
让options=person[“options”]作为![String]
self.tableArray.append(选项)
将name=person[“question”]设为!字符串
self.tableArray.append(选项)
}
让newDataSource:NH_DummyDataSourceModel=NH_DummyDataSourceModel(数组:人)
完成(新数据源)
}
}捕获{}
}捕获{}
}
}
那么,如何组合这两个数据源呢?在tableview的noofsection中应该编写什么代码呢

所以这些数据也需要放到那个表视图中。怎么办


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

为了简化操作,不需要应用独立的 类以作为viewModel。最好对一个tableView使用一个viewModel。 一种方法是扩展当前的webloadingModel,如下所示:

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

}

}
协议NHDummyViewModel{
静态变量datasection2:[字符串:Any]?{get set}
func loadFromDummyData(完成:@escaping(NH_DummyDataSourceModel?->())
}
扩展NHU问题视图模型:NHDummyViewModel{
静态变量datasection2:[字符串:任意]?
func loadFromDummyData(完成:@escaping(NH_DummyDataSourceModel?->()){
如果let path=Bundle.main.path(forResource:“jsonData”,类型为:“json”){
做{
让jsonData=try NSData(contentsOfFile:path,options:NSData.ReadingOptions.mappedIfSafe)
做{
让jsonResult:NSDictionary=try JSONSerialization.jsonObject(使用:jsonData作为数据,选项:JSONSerialization.ReadingOptions.mutableContainers)作为!NSDictionary
NH_QuestionViewModel.datasection2=jsonResult as![字符串:任意]
如果让people=jsonResult[“数据”]作为数组{
//self.dict=人
为人处事{
让options=person[“options”]作为![String]
self.tableArray.append(选项)
将name=person[“question”]设为!字符串
self.tableArray.append(选项)
}
让newDataSource:NH_DummyDataSourceModel=NH_DummyDataSourceModel(数组:人)
完成(新数据源)
}
}捕获{}
}捕获{}
}
}
}
我不知道实现细节,为什么需要datasection2。但是如果需要,可以使用类变量。然后在viewLoad中插入dummyViewModel方法,不需要更改任何其他内容。如果需要添加更多函数,请从此处添加。尽量避免使逻辑过于复杂

 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
override func viewDidLoad(){
super.viewDidLoad()
questionViewModel.loadData{(isSuccess)位于
如果(isSuccess==true)
{
self.questionViewModel.loadFromDummyData(完成:{(NH_DummyDataSourceModel))位于
设sec=self.questionViewModel.numberOfSections()

对于0中的uu..只需组合两个数据源并显示在tableview@rv7284请检查我已经添加了两个数据,一个来自json,另一个来自json.file。那么如何组合这两个数据源并在tableview中显示呢?首先从json文件存储阵列中获取数据,因为api响应需要时间,所以当响应到来时他将数据放入数组并重新加载表view@DevilDecoder但是根据我的代码怎么做。你能演示吗?如何实现?