How to Display Data From Api and Json.file - ios

I have two data's
1. From json
2. From json.file
Tha data format is below:-
{
"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"
]
}
]
}
This is my model:-
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)
}
}
Viewmodel in 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)
}
}}
dummy data viewmodel:-
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)
}
}
}
finally in the viewcontroller:-
in 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()
}
This is the format from json.file and also from the api.
I have used tableview.
So i need to list the header title from the key "question"
And the cell for row should display from the option keys.
So how to add this two data from the Json and Json.file?

You can create your models which represents your model. Preferably like
struct ResponseModel: Codable {
var data: [Question]?
}
struct QuestionModel{
var question: String?
var options: [String]?
}
Then after your Ajax post use
let responseData = try JSONDecoder().decode(AjaxResponse<ResponseModel>.self, from: data!)
Now you have your data.
You can then do in your UITableViewDeleates
//number of sections
resposnseData.data.count
//number of rows in section
responseData.data[section].options.count
//cell for index modify your cell using
response.data[indexPath.section].options[indexPath.row]
Hope it helps.

Related

how to use codable and decodable for the following json?

I have a following sample json file I want to do it with modal classes but am not sure how to do this in code.
{
"countryCodes": [{
"country_code": "AF",
"country_name": "Afghanistan",
"dialling_code": "+93"
},
{
"country_code": "AL",
"country_name": "Albania",
"dialling_code": "+355"
},
{
"country_code": "DZ",
"country_name": "Algeria",
"dialling_code": "+213"
},
{
"country_code": "AS",
"country_name": "American Samoa",
"dialling_code": "+1"
}
]
}
My modal class is as follows
import Foundation
class CountryModal : NSObject, NSCoding{
var countryCodes : [CountryCode]!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
countryCodes = [CountryCode]()
if let countryCodesArray = dictionary["countryCodes"] as? [[String:Any]]{
for dic in countryCodesArray{
let value = CountryCode(fromDictionary: dic)
countryCodes.append(value)
}
}
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if countryCodes != nil{
var dictionaryElements = [[String:Any]]()
for countryCodesElement in countryCodes {
dictionaryElements.append(countryCodesElement.toDictionary())
}
dictionary["countryCodes"] = dictionaryElements
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
countryCodes = aDecoder.decodeObject(forKey: "countryCodes") as? [CountryCode]
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
#objc func encode(with aCoder: NSCoder)
{
if countryCodes != nil{
aCoder.encode(countryCodes, forKey: "countryCodes")
}
}
}
and
import Foundation
class CountryCode : NSObject, NSCoding{
var countryCode : String!
var countryName : String!
var diallingCode : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
countryCode = dictionary["country_code"] as? String
countryName = dictionary["country_name"] as? String
diallingCode = dictionary["dialling_code"] as? String
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if countryCode != nil{
dictionary["country_code"] = countryCode
}
if countryName != nil{
dictionary["country_name"] = countryName
}
if diallingCode != nil{
dictionary["dialling_code"] = diallingCode
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
countryCode = aDecoder.decodeObject(forKey: "country_code") as? String
countryName = aDecoder.decodeObject(forKey: "country_name") as? String
diallingCode = aDecoder.decodeObject(forKey: "dialling_code") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
#objc func encode(with aCoder: NSCoder)
{
if countryCode != nil{
aCoder.encode(countryCode, forKey: "country_code")
}
if countryName != nil{
aCoder.encode(countryName, forKey: "country_name")
}
if diallingCode != nil{
aCoder.encode(diallingCode, forKey: "dialling_code")
}
}
}
How do I use these models to get the value of to say India +91 code? I am new to swift so I am clueless as to how to use these models.
the method I know is simple method of ditionary
fileprivate func loadNames(Country: String ) {
// //var countryCodes : [CountryCode]!
// var dict = [Coordinator]?.self
if let filePath = Bundle.main.path(forResource: "CountryCode", ofType: "json") {
if let jsonData = NSData(contentsOfFile: filePath) {
do {
// countryCodes = try? JSONDecoder().decode(CountryCode.self, from: jsonData as Data)
var countryCodes = try JSONSerialization.jsonObject(with: jsonData as Data, options: []) as? [String: Any]
// let countryCodes = try? JSONDecoder().decode(Welcome.self, from: jsonData as Data)
print ("country d ",countryCodes!)
let countryArray = countryCodes!["countryCodes"] as? NSArray
if countryArray!.count > 0
{
for countryElement in countryArray!
{
let dict = countryElement as! NSDictionary
if (dict["country_code"] as! String).description == countryCodeLocale
{
print("found ",(dict["dialling_code"] as! String ).description)
country_codeText.text = (dict["dialling_code"] as! String ).description
phone_NumberText.text = "99133131602"
return
}
}
}
} catch {
print(error.localizedDescription)
}
}
}
}
func fetchValues()
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Testing")
request.returnsObjectsAsFaults = false
do
{
let result = try context.fetch(request)
for data in result as! [NSManagedObject]
{
self.nameArr.append(data.value(forKey: "name") as! String)
self.lastNameArr.append(data.value(forKey: "lastname") as! String)
}
self.tableView.reloadData()
} catch {
print("Failed")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.nameArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? testTVCell
cell?.nameLbl.text = self.nameArr[indexPath.row]
cell?.lastNameLbl.text = self.lastNameArr[indexPath.row]
cell?.deleteBtn.tag = indexPath.row
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
#IBAction func deleteAction(_ sender: UIButton) {
// self.nameArr.remove(at: sender.tag)
// self.lastNameArr.remove(at: sender.tag)
// self.tableView.reloadData()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Testing")
fetchRequest.returnsObjectsAsFaults = false
let index = sender.tag
do
{
if let result = try? context.fetch(fetchRequest)
{
for object in result as! [NSManagedObject]
{
print(object.value(forKey: "name") as! String)
if ((object).value(forKey: "name") as! String).description == nameArr[index]
{
print(object.value(forKey: "name") as! String)
context.delete(object )
self.lastNameArr.remove(at: index)
self.nameArr.remove(at: index)
DispatchQueue.main.async
{
self.tableView.reloadData()
}
break
}
}
}
}
catch
{
print("error")
}
let _ : NSError! = nil
do {
try context.save()
self.tableView.reloadData()
} catch {
print("error : \(error)")
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Testing")
fetchRequest.returnsObjectsAsFaults = false
let index = indexPath.row
do
{
if let result = try? context.fetch(fetchRequest)
{
for object in result as! [NSManagedObject]
{
print(object.value(forKey: "name") as! String)
if ((object).value(forKey: "name") as! String).description == nameArr[index]
{
print(object.value(forKey: "name") as! String)
context.delete(object )
DispatchQueue.main.async
{
}
}
}
}
}
catch
{
print("error")
}
let _ : NSError! = nil
do {
try context.save()
} catch {
print("error : \(error)")
}
self.lastNameArr.remove(at: index)
self.nameArr.remove(at: index)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
#IBAction func submitTapped(_ sender: Any)
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Testing", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue(self.nameTxt.text, forKey: "name")
newUser.setValue(self.lastNameTxt.text, forKey: "lastname")
do
{
try context.save()
}
catch
{
print("Failed saving")
}
}
func apiCall()
{
let urlString = "https://example.org"
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(url: url! as URL)
activityView.startAnimating()
self.view.addSubview(activityView)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
if error != nil
{
DispatchQueue.main.async
{
let alert = UIAlertController(title: "Network Connection Lost", message: "Please try again", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: { Void in
self.activityView.stopAnimating()
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
return
}
do
{
let result = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
print(" JSON : ", result)
let a = result as! NSArray
let b = a[0] as! NSDictionary
print("name ", (b["Name"] as! String).description)
var nameArray = [String]()
for element in a
{
nameArray.append(((element as! NSDictionary)["Name"] as! String).description)
}
print("nameArray ", nameArray)
DispatchQueue.main.async
{
self.activityView.stopAnimating()
self.activityView.isHidden = true
}
}
catch
{
print("Error -> \(error)")
DispatchQueue.main.async
{
self.activityView.stopAnimating()
let alert = UIAlertController(title: "Alert?", message: error as? String,preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
}
}
task.resume()
}
}
let indexpath = NSIndexPath(row: sender.tag, section: 0)
let cell = tableView.cellForRow(at: indexpath as IndexPath) as? testTVCell
if (self.tableView.isEditing) {
cell?.deleteBtn.setTitle("Edit", for: .normal)
self.tableView.setEditing(false, animated: true)
} else {
cell?.deleteBtn.setTitle("Done", for: .normal)
self.tableView.setEditing(true, animated: true)
}
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let urlString = appDelegate.serverUrl + "queryClassifiedList"
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(url: url! as URL)
let spinner = JHSpinnerView.showDeterminiteSpinnerOnView(self.view)
spinner.progress = 0.0
self.view.addSubview(spinner)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
var dict : [AnyHashable: Any] = [
"channel" : appDelegate.channel,
"device" : appDelegate.deviceId,
"classifiedtype" : self.classifiedType,
"startnum" : startNum,
"endnum" : endNum
]
if UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int != nil && UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int != -1
{
let categoryRow = (UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int)!
dict["categoryid"] = categoryRow
}
if UserDefaults.standard.value(forKey: "cityRowFilter") as? Int != nil && UserDefaults.standard.value(forKey: "cityRowFilter") as? Int != -1
{
let cityId = (UserDefaults.standard.value(forKey: "cityRowFilter") as? Int)!
dict["city"] = cityId
}
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: dict, options: [])
request.httpBody = jsonData
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let urlString = appDelegate.serverUrl + "queryClassifiedList"
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(url: url! as URL)
let spinner = JHSpinnerView.showDeterminiteSpinnerOnView(self.view)
spinner.progress = 0.0
self.view.addSubview(spinner)
request.httpMethod = "POST"
var bodyData : String!
bodyData = "channel=" + appDelegate.channel + "&device=" + appDelegate.deviceId + "&Classifiedtype=" + self.classifiedType.description + "&Startnum=" + startNum.description + "&Endnum=" + endNum.description
if UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int != nil && UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int != -1
{
let categoryRow = (UserDefaults.standard.value(forKey: "categoryClassifiedFilter") as? Int)!
bodyData = bodyData + "&Categoryid=" + categoryRow.description
}
if UserDefaults.standard.value(forKey: "cityRowFilter") as? Int != nil && UserDefaults.standard.value(forKey: "cityRowFilter") as? Int != -1
{
let cityId = (UserDefaults.standard.value(forKey: "cityRowFilter") as? Int)!
bodyData = bodyData + "&city=" + cityId.description
}
print("bodyData : ", bodyData)
request.httpBody = bodyData.data(using: String.Encoding.utf8)
}
but I want modal class method implementation. Can someone help?
You can try
struct Root: Codable {
let countryCodes: [CountryCode]
}
struct CountryCode: Codable {
let countryCode, countryName, diallingCode: String
enum CodingKeys: String, CodingKey {
case countryCode = "country_code"
case countryName = "country_name"
case diallingCode = "dialling_code"
}
}
let res = try? JSONDecoder().decode(Root.self,from:jsonData)
print(res.countryCodes)
res.countryCodes.forEach {
if $0.countryCode == "DZ" {
print($0.diallingCode)
}
}

How to merge two datasourcemodel using mvvm in swift

I have two datasource model.I am doing in mvvm.
My datasourcemodel is as below.
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)
}
}
the above is first datasourcemodel.
Next datasourcemodel is as below.
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)
}
}
In my view controller :-
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)
}
}
MY 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)
}
}
}
my dummyViewModel is below:-
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)
}
}
}
Now i need to merge this two datasourceModel.
I am using tableview to display the data .
So first i need to display the data from the JSON.then below i need to display the data from the json.file.So how to merge this two datasourcemodel.
First the data from JSON has 10 sections.
In json.file it has 3 sections.So total 13 sections .So i need to display the 13 sections together in the tableview.How to do?
This the json.file data:-
{
"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"]
}
]
}
And same format forJSON from 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"]
}
]
}
class OptionsModel: NSObject {
var options: [String]?
var question: String?
var button_type: String?
}
class OptionsViewModel: NSObject {
var optionList: Array<OptionsModel>?
func callApi() {
yourApiCall() { webResponseArray in
for res in webResponseArray {
let model = OptionsModel(json: res)
if optionList == nil {
optionList = [OptionsModel]()//Initialize Array if not initialized
}
optionList.append(model)// You are appending Option getting from web Api Response
}
//After Completely fetching all models from webResponseArray you should load Data from Local JSON
loadLocalJSON()//After loading Data from Web You are loading Data from local JSON.
}
}
func loadLocalJSON() {
let localJsonArray = someMethodToLoadJsonFromLocalFileAndReturnsJSON()
for json in localJsonArray {
let model = OptionsModel(json: json)
if optionList == nil {
optionList = [OptionsModel]()//Initialize Array if not initialized
}
optionList.append(model)// You are appending Option getting from Local JSON
}
//Now you have a single Array containing all local and remote option models.
}
}

Firebase Database indexPath

I'm trying to retrieve data from firebase using this function but I'm not getting all the data:
func retrieveVideos(_ completionBlock: #escaping (_ success: Bool, _ error: Error?) -> ()) {
let userMessagesRef = DataService.instance.REF_ARTISTARTS.child(Auth.auth().currentUser!.uid)
userMessagesRef.observe(.childAdded, with: { [weak self] (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
print("SNAPSHOT: (snapshot.count)") = 12
}
guard let strongSelf = self else {return}
guard let dictionary = snapshot.value as? [String: AnyObject] else {
completionBlock(false, nil)
return
}
var arts = [Art?]()
if let art = ArtViewModelController.parse(dictionary) {
arts.append(art)
print(arts.count) = 1
}
strongSelf.viewModels = ArtViewModelController.initViewModels(arts)
completionBlock(true, nil)
}) { (error: Error) in
completionBlock(false, error)
}
}
var viewModelsCount: Int {
return viewModels.count
}
func viewModel(at index: Int) -> ArtViewModel? {
guard index <= 0 && index < viewModelsCount else { return nil }
return viewModels[index]
}
}
private extension ArtViewModelController {
static func parse(_ dictionary: [String: Any]) -> Art? {
let artID = dictionary["artID"] as? String ?? ""
let imgUrl = dictionary["imageUrl"] as? String ?? ""
let title = dictionary["title"] as? String ?? ""
let description = dictionary["description"] as? String ?? ""
let price = dictionary["price"] as? NSNumber ?? 0
let type = dictionary["type"] as? String ?? ""
let height = dictionary["height"] as? NSNumber ?? 0
let width = dictionary["width"] as? NSNumber ?? 0
let postDate = dictionary["postDate"] as? NSNumber ?? 0
return Art(artID: artID, imgUrl: imgUrl, price: price, title: title, description: description, type: type, height: height, width: width, postDate: postDate)
}
static func initViewModels(_ arts: [Art?]) -> [ArtViewModel?] {
print("SECOND VIDEO COUNT: \(arts.count)")
return arts.map { art in
if let art = art {
return ArtViewModel(art: art)
} else {
return nil
}
}
}
}
My problem is that my index.count is always equal to 1 but it's supposed to equal to 12.
Here's the original code:
func retrieveUsers(_ completionBlock: #escaping (_ success: Bool, _ error: NSError?) -> ()) {
let urlString = "http://localhost:3000/users"
let session = URLSession.shared
guard let url = URL(string: urlString) else {
completionBlock(false, nil)
return
}
let task = session.dataTask(with: url) { [weak self] (data, response, error) in
guard let strongSelf = self else { return }
guard let data = data else {
completionBlock(false, error as NSError?)
return
}
let error = NSError.createError(0, description: "JSON parsing error")
if let jsonData = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]] {
guard let jsonData = jsonData else {
completionBlock(false, error)
return
}
var users = [User?]()
for json in jsonData {
if let user = UserViewModelController.parse(json) {
users.append(user)
}
}
strongSelf.viewModels = UserViewModelController.initViewModels(users)
completionBlock(true, nil)
} else {
completionBlock(false, error)
}
}
task.resume()
}
So I'm trying to do the same thing but with Firebase. If you need more details please just ask!
SNAPSHOT PRINT:
SNAPSHOT: Optional({
description = "Yes ";
height = 87;
imageUrl = "https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2FB6E2A9F0-C409-4732-B6D9-14382E6796F5?alt=media&token=32992b9c-4a08-456d-8950-119f681b4cdc";
postDate = 1498921599547;
price = 23;
private = 0;
title = "Yes ";
type = Modern;
userUID = 4bjurh5FFNOUb2D4oHGfRqEm7Il2;
width = 71;
})
SNAPSHOT: Optional({
artHeight = 85;
artWidth = 123;
description = "Yes ";
height = 85;
imageUrl = "https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F16280189-5AEA-47CB-9251-C95635FFE56C?alt=media&token=8198df4e-da8c-4883-b278-fc7c14730f69";
postDate = 1498921623601;
price = 23;
private = 0;
title = "blacks don\U2019t Crack ";
type = Abstract;
userUID = 4bjurh5FFNOUb2D4oHGfRqEm7Il2;
width = 123;
})
SNAPSHOT: Optional({
artHeight = 81;
artWidth = 11;
description = "Yes ";
height = 81;
imageUrl = "https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F305FDE5C-1C5C-4ABD-B4A1-4FA224421202?alt=media&token=fcba57df-e252-47c2-be92-7836bd97e6fe";
postDate = 1502242913081;
price = 23;
private = 0;
title = "Title ";
type = type;
userUID = 4bjurh5FFNOUb2D4oHGfRqEm7Il2;
width = 118;
})
SNAPSHOT: Optional({
description = "Hey ";
height = 82;
imageUrl = "https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F04B00727-2AE4-41E3-BCA3-3980182C7F67?alt=media&token=cc1d6a92-1625-453c-bf1f-2ec84d6df51a";
postDate = 1503341277594;
price = 23;
private = 0;
title = "Title ";
type = Modern;
userUID = 4bjurh5FFNOUb2D4oHGfRqEm7Il2;
width = 124;
})
DIC: ["height": 87, "private": 0, "width": 71, "postDate": 1498921599547, "description": Yes , "title": Yes , "imageUrl": https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2FB6E2A9F0-C409-4732-B6D9-14382E6796F5?alt=media&token=32992b9c-4a08-456d-8950-119f681b4cdc, "userUID": 4bjurh5FFNOUb2D4oHGfRqEm7Il2, "price": 23, "type": Modern]
DIC: ["artWidth": 123, "height": 85, "private": 0, "artHeight": 85, "description": Yes , "postDate": 1498921623601, "width": 123, "imageUrl": https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F16280189-5AEA-47CB-9251-C95635FFE56C?alt=media&token=8198df4e-da8c-4883-b278-fc7c14730f69, "title": blacks don’t Crack , "price": 23, "type": Abstract, "userUID": 4bjurh5FFNOUb2D4oHGfRqEm7Il2]
DIC: ["artWidth": 11, "height": 81, "private": 0, "artHeight": 81, "description": Yes , "postDate": 1502242913081, "width": 118, "imageUrl": https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F305FDE5C-1C5C-4ABD-B4A1-4FA224421202?alt=media&token=fcba57df-e252-47c2-be92-7836bd97e6fe, "title": Title , "price": 23, "type": type, "userUID": 4bjurh5FFNOUb2D4oHGfRqEm7Il2]
DIC: ["height": 82, "private": 0, "width": 124, "postDate": 1503341277594, "description": Hey , "title": Title , "imageUrl": https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Art%2F4bjurh5FFNOUb2D4oHGfRqEm7Il2%2F04B00727-2AE4-41E3-BCA3-3980182C7F67?alt=media&token=cc1d6a92-1625-453c-bf1f-2ec84d6df51a, "userUID": 4bjurh5FFNOUb2D4oHGfRqEm7Il2, "price": 23, "type": Modern]
Could you please attach the output of print(dictionary) and print(snapshot.value) before calling ArtViewModelController.parse(dictionary)?
var arts = [Art?]()
print(dictionary) // -> output #1
print(snapshot.value) // -> output #2
if let art = ArtViewModelController.parse(dictionary) {
arts.append(art)
[...]
You could try the following two options.
Option #1
This should work with the assumption that snapshot.value returns the full dictionary (array of 12 items):
func retrieveVideos(_ completionBlock: #escaping (_ success: Bool, _ error: Error?) -> ()) {
let userMessagesRef = DataService.instance.REF_ARTISTARTS.child(Auth.auth().currentUser!.uid)
userMessagesRef.observe(.childAdded, with: { [weak self] (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
completionBlock(false, nil)
return
}
guard let strongSelf = self else {return}
var arts = [Art?]()
if let art = ArtViewModelController.parse(dictionary) {
arts.append(art)
}
strongSelf.viewModels = ArtViewModelController.initViewModels(arts)
completionBlock(true, nil)
}) { (error: Error) in
completionBlock(false, error)
}
}
Option #2
If it works, Option #1 is the simpler solution. Otherwise, as it looks like the content of each DataSnapshot is a dictionary, the following code may work:
func retrieveVideos(_ completionBlock: #escaping (_ success: Bool, _ error: Error?) -> ()) {
let userMessagesRef = DataService.instance.REF_ARTISTARTS.child(Auth.auth().currentUser!.uid)
userMessagesRef.observe(.childAdded, with: { [weak self] (snapshot) in
guard let strongSelf = self else {return}
var arts = [Art?]()
for snapshotItem in snapshot.children.allObjects as? Dictionary {
let art = Art(snapshot: snapshotItem)
arts.append(art)
}
strongSelf.viewModels = ArtViewModelController.initViewModels(arts)
completionBlock(true, nil)
}
}) { (error: Error) in
completionBlock(false, error)
}
You should add Art(snapshot: Dictionary) to the Art class:
// Initialize Art from dictionary
func Art(snapshot: Dictionary) {
let artID = dictionary["userUID"] as? String ?? ""
let imgUrl = dictionary["imageUrl"] as? String ?? ""
let title = dictionary["title"] as? String ?? ""
let description = dictionary["description"] as? String ?? ""
let price = dictionary["price"] as? NSNumber ?? 0
let type = dictionary["type"] as? String ?? ""
let height = dictionary["artHeight"] as? NSNumber ?? 0
let width = dictionary["artWidth"] as? NSNumber ?? 0
let postDate = dictionary["postDate"] as? NSNumber ?? 0
return Art(artID: artID, imgUrl: imgUrl, price: price, title: title, description: description, type: type, height: height, width: width, postDate: postDate)
}
NOTE: I assumed the key you are looking for in the DataSnapshot is userUID as I didn't see an artID (as is in the parsing code).
Use This: -
func retrieveVideos(_ completionBlock: #escaping (_ success: Bool, _ error: Error?) -> ()) {
let userMessagesRef = DataService.instance.REF_ARTISTARTS.child(Auth.auth().currentUser!.uid)
userMessagesRef.observe(.value, with: { [weak self] (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot]
{
print("SNAPSHOT: (snapshots.count)")
}
var arts = [Art]()
guard let strongSelf = self else {return}
for snapshot in snapshots {
let dictionary = snapshot.value as? [String: AnyObject]
if let art = ArtViewModelController.parse(dictionary) {
arts.append(art)
}
}
strongSelf.viewModels = ArtViewModelController.initViewModels(arts)
completionBlock(true, nil)
}) { (error: Error) in
completionBlock(false, error)
}
}

Swift 3.0 and web service

Attempting to read our web service into a UITableViewController and it only returns the first record to the simulator. So hoping that someone will be able to look at the code and guide me down the correct path. Ultimate goal is to get it into a UITableViewCell so I can format nicely but just looking to get all the records.
Here is a view of the partial json file that will be returned.
{
"Count":11518,
"Result":[
{
"cuName": "#1",
"charter_Num":
"16328","City":
"Jonesboro",
"State_id": "GA",
"cuName_location": "#1 - Jonesboro, GA"
},
{
"cuName": "#lantec Financial",
"charter_Num": "7965",
"City": "Virginia Beach",
"State_id": "VA",
"cuName_location": "#lantec Financial - Virginia Beach, VA"
}]
}
Here is the code that reads in the json web service and attempts to parse and put in the table.
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
//Commented out the following lines because it doesn't return anything when using the modified code that works
//
// guard let data_list = json as? NSArray else
// {
// return
// }
//This code works but only gives me the 1st record back
if let cu_list = try? json as? [String:Any],
let result = cu_list?["Result"] as? [[String:Any]],
let charter_num = result[0]["charter_Num"] as? String,
let value = result[0]["cuName_location"] as? String, result.count > 0 {
TableData.append(value + " (" + charter_num + ")")
} else {
print("bad json - do some recovery")
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
You are referring the 0th index element from result object and it will only return the 1st record from JSON data. You need to run thru the loop and append the data to array which you need to use for populating the data in UITableView.
func GetCategoryData(){
//get_high_score.php?from=1472409001482&number=10&to=1493657787867
let checklaun = UserDefaults.standard.integer(forKey: "Language")
if checklaun == 1 {
EZLoadingActivity.show("Loading...", disableUI: false)
}else{
EZLoadingActivity.show("جار التحميل...", disableUI: false)
}
DispatchQueue.global(qos: .background).async {
let myUrl = URL(string: GlobleUrl.BASEURL + "advertise_list.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "GET"
// let fromvalue = 1472409001482
// let numbervalue = 10
// let tovalue = 1493657787867
let postString = ""//"from=" + fromvalue + "&" + "number=" + numbervalue + "&" + "to=" + tovalue
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
EZLoadingActivity.hide(false, animated: true)
print("error=\(error)")
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
DispatchQueue.main.async {
if let parseJSON = json {
print(parseJSON)
let status = parseJSON["status"] as! Bool
if status == true{
EZLoadingActivity.hide(true, animated: false)
self.categoryDataArray = parseJSON["data"] as! NSMutableArray
print("\(self.categoryDataArray)")
self.filterarray = parseJSON["fixed_cat"] as! NSMutableArray
let teamp = self.categoryDataArray .value(forKey: "main_image") as AnyObject
print("\(teamp)")
self.categoryImageArray.setArray(teamp as! [Any])
print("\( self.categoryImageArray)")
// let teamp = self.data .value(forKey: "name") as AnyObject
// print("\(teamp)")
// self.categoryNameArray.setArray(teamp as! [Any])
self.allcategoryTableViewCell.reloadData()
self.allcategoryfilterlistview.reloadData()
// self.tblscoreList.reloadData()
}else{
EZLoadingActivity.hide(false, animated: true)
}
}
}
}
catch {
EZLoadingActivity.hide(false, animated: true)
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print(error)
}
}
task.resume()
}
}

Access JSON array inside another array

So far I only had to deal with simple JSON arrays with only a single array. I have now combined 2 arrays together so I can get my user data and all the reviews for that user:
[
{
"user_id": "16",
"name": "Jonh",
"lastName": "appleseed",
"username": "jonh#me.com",
"sex": "male",
"image_url": "",
"review": [
{
"reviewID": "4",
"merchant_id": "17",
"rating": "5",
"user_id": "16",
"comments": "Very good customer. Strongly suggested",
"date": "0000-00-00",
"reviewYear": "",
"publish": "1"
},
{
"reviewID": "8",
"merchant_id": "16",
"rating": "2",
"user_id": "16",
"comments": "Automatic review due to "NO SHOW" without informing the merchant",
"date": "0000-00-00",
"reviewYear": "",
"publish": "1"
}
]
}
]
before I added the reviews my model looked like this:
import Foundation
class Users {
let userImage:String?
let name:String?
let sex:String?
let image_url:String?
init(dictionary:NSDictionary) {
userImage = dictionary["userImage"] as? String
name = dictionary["name"] as? String
sex = dictionary["sex"] as? String
image_url = dictionary["image_url"] as? String
}
}
func loadUser(completion:(([Users])-> Void), userId: String){
let myUrl = NSURL(string: "http://www.myWebSite.com/api/v1.0/users.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "user_id=\(userId)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print("error\(error)")
} else {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
print(json)
var users = [Users]()
for user in json{
let user = Users(dictionary: user as! NSDictionary)
users.append(user)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0 )){
dispatch_async(dispatch_get_main_queue()){
completion(users)
}
}
}
} catch{
}
}
}
task.resume()
}
which I could then used in my viewController:
func loadModel() {
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "updating your deals..."
users = [Users]()
let api = Api()
api.loadUser(didLoadUsers , userId: "16")
}
func didLoadUsers(users:[Users]){
self.users = users
self.tableView.reloadData()
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
Can I get the review field so I can present it in a table view controller?
I added to your Users class an array of reviews that will be populated in your user init() method. I recommend you to take look at struct Review and make your user class a struct, and change your NSDictionary to swift Dictionary.
struct Review {
let reviewID:String?
let merchant_id:String?
let user_id:String?
//to be continued with your own implementation...
init(dictionary:[String:String]) {
reviewID = dictionary["reviewID"]
merchant_id = dictionary["merchant_id"]
user_id = dictionary["user_id"]
//to be continued with your own implementation...
}
}
class Users {
let userImage:String?
let name:String?
let sex:String?
let image_url:String?
var reviews:[Review]
init(dictionary:[String:AnyObject]) {
userImage = dictionary["userImage"] as? String
name = dictionary["name"] as? String
sex = dictionary["sex"] as? String
image_url = dictionary["image_url"] as? String
reviews = [Review]()
if let userReviews = dictionary["review"] as? [[String:AnyObject]] {
for review in userReviews {
if let unwrapedReview = review as? [String:String] {
let r = Review(dictionary: unwrapedReview)
reviews.append(r)
}
}
}
}
}
Also I recommend you in the future to use SwiftyJSON for parsing JSON and also Alamofire for networking requests.
Done. It was easier than what I thought. I just had to add a UserReview class and change the signature of loadUser function:
func loadUser(completion:((user: [Users], review: [UserReview])-> Void), userId: String){
let myUrl = NSURL(string: "http://www.myWebsite.com/api/v1.0/users.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "user_id=\(userId)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print("error\(error)")
}else{
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
var users = [Users]()
for user in json{
let user = Users(dictionary: user as! NSDictionary as! [String : AnyObject])
users.append(user)
//*********** now I can access the reviews from my son***************
let reviewArray = json[0]["review"] as! NSArray
var reviews = [UserReview]()
for review in reviewArray{
let review = UserReview(dictionary: review as! NSDictionary as! [String : AnyObject])
reviews.append(review)
}
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0 )){
dispatch_async(dispatch_get_main_queue()){
completion(user: users, review: reviews)
}
}
}
} catch{
}
}
}
task.resume()
}
So I can use it in my tableViewController
var users: [Users]?
var reviews: [UserReview]?
func loadModel() {
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "updating..."
users = [Users]()
reviews = [UserReview]()
let api = Api()
api.loadUser(didLoadUsers , userId: "16")
}
func didLoadUsers(users:[Users], reviews:[UserReview] ){
self.users = users
self.reviews = reviews
self.tableView.reloadData()
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return users!.count
}
if section == 1 {
return 1
}
if section == 2 {
return reviews!.count
}
return 0
}
So in my cellForRowAtIndexPath I can now load all the reviews
if indexPath.section == 2 {
let review = reviews![indexPath.row]
let reviewCell = tableView.dequeueReusableCellWithIdentifier("reviewCell", forIndexPath: indexPath) as! UserReviewsTableViewCell
reviewCell.useReview(review)
return reviewCell
}

Resources