如何显示来自Api和Json.file的数据

时间:2018-09-28 06:42:31

标签: ios arrays json swift

我有两个数据 1.从json 2.从json.file

Tha数据格式如下:-

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

这是我的模特:-

enum NHAnswerType:Int
{
     case NHAnswerCheckboxButton = 1
     case NHAnswerRadioButton

     case NHAnswerSmileyButton
     case NHAnswerStarRatingButton

     case NHAnswerTextButton
}

class NH_QuestionListModel: NSObject {

    var dataListArray33:[NH_OptionsModel] = []

    var id:Int!
    var question:String!
    var buttontype:String!
    var options:[String]?
    var v:String?
    var answerType:NHAnswerType?

    var optionsModelArray:[NH_OptionsModel] = []
    init(dictionary :JSONDictionary) {

        guard   let question = dictionary["question"] as? String,
            let typebutton = dictionary["button_type"] as? String,

                let id = dictionary["id"] as? Int
             else {
                return

        }
       // (myString as NSString).integerValue

        self.answerType = NHAnswerType(rawValue: Int(typebutton)!)

        if let options = dictionary["options"] as? [String]{
           print(options)

            for values in options{
                print(values)
                let optionmodel = NH_OptionsModel(values: values)
                self.optionsModelArray.append(optionmodel)
            } 
        }

        self.buttontype = typebutton
        self.question = question
        self.id = id
    }
  }

optionmodel:-

class NH_OptionsModel: NSObject {

    var isSelected:Bool? = false
    var textIndexPath :IndexPath?

    var dummyisSelected:Bool? = false

    var v:String?
        var values:String?

     init(values:String) {
           self.values = values
           print( self.values)
        }
  }

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)

                   // let data2 = wholedata["data"] as? [String:Any]
                        self.datasection1 = wholedata

                    if  let data1 = wholedata["data"] as? Array<[String:Any]>{
                        print(data)
                        print(response)

                        for question in data1 {
                            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: data1)

                        completion(newDataSource)
                    }
                }

            case .failure(let encodingError ):
                print(encodingError)

                //  if response.response?.statusCode == 404{
                print(encodingError.localizedDescription)

                completion(nil)
            }
        }}

虚拟数据视图模型:-

  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]

            let people1  = jsonResult["data"] as? [String:Any]
            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 {}
  } 
}

 func loadData1(completion :@escaping (_ isSucess:Bool) -> ()){

 loadFromDummyData{ (newDataSourceModel) in

    if(newDataSourceModel != nil)
    {
        self.datasourceModel = newDataSourceModel!
        completion(true)
    }
    else{
        completion(false)
     }
  }
}

最后在viewcontroller中:-

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

               self.item1 = [self.questionViewModel.datasection1]

               self.activityindicator.stopAnimating()
               self.activityindicator.isHidden = true
               self.tableview.refreshControl = refreshControl
               self.tableview .allowsMultipleSelection = false
               self.tableview.reloadData()

                self.dummyDataViewModel.loadData1{ (isSuccess) in

                    if(isSuccess == true)
                    {

                    }
                    else{
                     self.viewDidLoad() 
                    }
                }
            }
            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)
            }
            self.sections = [Category(name:"A",items:self.item1),
                        Category(name:"B",items:self.item2),
            ]

            print(self.sections)
             self.tableview.reloadData()
        }

这是来自json.file和api的格式。 我用过tableview。

所以我需要从“问题”键中列出标题标题

该行的单元格应通过选项键显示。

那么如何从JsonJson.file添加这两个数据?

1 个答案:

答案 0 :(得分:0)

您可以创建代表您的模型的模型。最好像

struct ResponseModel: Codable {
 var data: [Question]?
}

struct QuestionModel{
 var question: String?
 var options: [String]?
}

然后在使用Ajax后

let responseData = try JSONDecoder().decode(AjaxResponse<ResponseModel>.self, from: data!)

现在您有了数据。

然后您可以在UITableViewDeleates中完成

//节数

resposnseData.data.count

//节中的行数

responseData.data[section].options.count

//用于索引的单元格使用

response.data[indexPath.section].options[indexPath.row]

希望有帮助。