У меня есть две модели источника данных. Я делаю в mvvm.
Моя модель источника данных, как показано ниже.
class QuestionDataSourceModel: NSObject {
var dataListArray:Array<QuestionListModel>? = []
var list:Array<OptionsModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
// newArray = self.getJsonDataStored22()
}
else{
newArray = array!
}
var datalist:Array<QuestionListModel> = []
for dict in newArray{
let model = QuestionListModel(dictionary: dict)
datalist.append(model)
}
self.dataListArray = datalist
print(self.dataListArray)
}
}
выше - первая модель источника данных.
Следующая модель источника данныхкак показано ниже.
class DummyDataSourceModel: NSObject {
var dataListArray:Array<DummyDataModel>? = []
var list:Array<DummyDataModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
// newArray = self.getJsonDataStored22()
}
else{
newArray = array!
}
var datalist:Array<DummyDataModel> = []
for dict in newArray{
let model = DummyDataModel(dictionary: dict)
datalist.append(model)
}
self.dataListArray = datalist
print(self.dataListArray)
}
}
На мой взгляд контроллер: -
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()
// self.questionViewModel.loadData2{ (isSuccess) in
self.dummyDataViewModel.loadData1{ (isSuccess) in
if(isSuccess == true)
{
print(self.questionViewModel.datasourceModel.dataListArray?.count)
self.questionViewModel.totaldata()
self.tableview2.allowsMultipleSelection = false
self.tableview2.reloadData()
}
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)
}
}
МОЙ QuestionViewModel: -
func loadFromWebserviceData(completion :@escaping (QuestionDataSourceModel?) -> ()){
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)
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:QuestionDataSourceModel = QuestionDataSourceModel(array: data)
completion(newDataSource)
}
}
case .failure(let encodingError ):
print(encodingError)
// if response.response?.statusCode == 404{
print(encodingError.localizedDescription)
completion(nil)
}
}}
func loadData(completion :@escaping (_ isSucess:Bool) -> ()){
loadFromWebserviceData { (newDataSourceModel) in
if(newDataSourceModel != nil)
{
self.datasourceModel = newDataSourceModel!
completion(true)
}
else{
completion(false)
}
}
}
мой dummyViewModel ниже: -
func loadFromDummyData(completion :@escaping (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
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:DummyDataSourceModel = 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)
}
}
}
Теперь мне нужно объединить эти два datasourceModel.
Я использую таблицу для отображения данных.
Итак, сначала мне нужно отобразить данные из JSON.then ниже.Мне нужно отобразить данные из json.file. Так как объединить эти две модели источника данных.
Сначала данные из JSON имеют 10 разделов.В json.file есть 3 раздела. Всего 13 разделов. Так что мне нужно отобразить 13 разделов вместе в табличном представлении. Как это сделать?
Это данные 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"]
}
]
}
И тот же формат для JSON из API.
{
"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"]
}
]
}