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.
}
}
Related
Here's the func that I want the for loop to wait for the completion from func getVenueDetails and if completion is true break out of the loop, and if not continue with the next venue id.
func searchVenues(lat: Double, lng: Double) {
let parameter: [String: String] = [
"ll": "\(lat),\(lng)",
"radius": "600",
"limit": "10",
"intent": "browse",
"categoryId": "4bf58dd8d48988d1e4931735,4bf58dd8d48988d1f1931735,4deefb944765f83613cdba6e,4bf58dd8d48988d17f941735,52e81612bcbc57f1066b79eb,4bf58dd8d48988d181941735,4bf58dd8d48988d1f4931735,4bf58dd8d48988d189941735,4bf58dd8d48988d182941735,4bf58dd8d48988d17b941735,4bf58dd8d48988d163941735,4bf58dd8d48988d164941735,4bf58dd8d48988d165941735,56aa371be4b08b9a8d57356a,4bf58dd8d48988d12f941735"
];
var isSent2: Bool = false
client.request(path: "venues/search", parameter: parameter) { result in
switch result {
case let .success(data):
let jsonResponse = try! JSONSerialization.jsonObject(with: data, options: [])
let json = JSON(jsonResponse)
let name = json["response"]["venues"][0]["name"].string
print("NAME FROM JSON: ", name)
let id = json["response"]["venues"][0]["id"].string
print("id of foursquare", id)
let group = DispatchGroup()
group.notify(queue: .main) {
for (key,subJson):(String, JSON) in json["response"]["venues"] {
//group.enter()
let placeName = subJson["name"].string
print("place name:",placeName.unsafelyUnwrapped)
let placeId = subJson["id"].string
print("place id:",placeId.unsafelyUnwrapped)
group.enter()
self.getVenueDetails(id: placeId!) { (isSent) in
print("isSent", isSent)
isSent2 = isSent
group.leave()
}
if (isSent2){
print("linaaa")
//group.leave()
break
}
}//end of for loop
}
// print("json == ", jsonResponse)
case let .failure(error):
// Error handling
switch error {
case let .connectionError(connectionError):
print(connectionError)
case let .responseParseError(responseParseError):
print(responseParseError) // e.g. JSON text did not start with array or object and option to allow fragments not set.
case let .apiError(apiError):
print(apiError.errorType) // e.g. endpoint_error
print(apiError.errorDetail) // e.g. The requested path does not exist.
}
}
}
}
here's the other function, where the request for venue details is made, so I want when the isSent returned true the for loop in searchVenues to stop (break) and if returned false to continue with next one.
func getVenueDetails(id: String, completionHandler: #escaping (Bool)->Void) {
var isSent: Bool = false
let parameter: [String: String] = [
"VENUE_ID": "\(id)",
];
client.request(path: "venues/\(id)", parameter: parameter) { result in
switch result {
case let .success(data):
let jsonResponse = try! JSONSerialization.jsonObject(with: data, options: [])
let json = JSON(jsonResponse)
// print("json == ", jsonResponse)
let name = json["response"]["venue"]["name"].string
if let rating:Double = json["response"]["venue"]["rating"].double {
print("rating from: ", rating)
//rat = rating
if (rating > 2) {
self.foursquareNotification(name: name!)
print("here inside lol")
isSent = true
DispatchQueue.main.async {
completionHandler(isSent)
print("isSent hereee", isSent)
}
} //end if
else {
isSent = false
DispatchQueue.main.async {
completionHandler(isSent)
}
}//end else
} //end if rating
// rat = json["response"]["venue"]["rating"].double!
// print("rating from: ", rat)
// //rat = rating.unsafelyUnwrapped
case let .failure(error):
// Error handling
switch error {
case let .connectionError(connectionError):
print(connectionError)
case let .responseParseError(responseParseError):
print(responseParseError) // e.g. JSON text did not start with array or object and option to allow fragments not set.
case let .apiError(apiError):
print(apiError.errorType) // e.g. endpoint_error
print(apiError.errorDetail) // e.g. The requested path does not exist.
}
}
}
//return isSent
}//end getVenueDetails
You need to remove the for loop
var res = json["response"]["venues"]
Then
var current = 0
func start(item:ItemType) {
let placeName = subJson["name"].string
let placeId = subJson["id"].string
self.getVenueDetails(id: placeId!) { (isSent) in
if isSent {
counter += 1
start(nextItem)
}
}
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.
I want to change my label text after getting a response from the server but it doesn't change after getting a response from server!!
here is my code :
func getOrderCost() {
DispatchQueue.main.async {
self.customView?.setOrderPriceEstimate(price: "۰")
var price = 10
if let p_code = self.customView?.getPromotionCode() {
self.orderPriceObject.promotion_code = p_code
}
self.registerOrderVM.getOrderPriceEstimation(orderInfo: self.orderPriceObject).asObservable().subscribe(onNext: { (response) in
if let res = response as? [String: Int], let p = res["price_with_added_value"] {
self.customView?.setOrderPriceEstimate(price: "cost : \(p)")
}
}, onError: { (error) in
self.view.showMessage(error.localizedDescription, type: .error, options: [.hideOnTap(true)])
}).disposed(by: self.disposeBag)
}
}
and this is the setOrderPriceEstimate function in customView :
public func setOrderPriceEstimate(price: String) {
self.orderCostLbl.text = price
}
DispatchQueue.main.async {
self.customView?.setOrderPriceEstimate(price: "cost : \(p)")
}
I think you have to update UI in main thread.
Making DispatchQueue.main.async outer doesn't guarantee that code inside getOrderPriceEstimation will run in main queue as code inside getOrder may be in other thread
func getOrderCost() {
DispatchQueue.main.async {
self.customView?.setOrderPriceEstimate(price: "۰")
var price = 10
if let p_code = self.customView?.getPromotionCode() {
self.orderPriceObject.promotion_code = p_code
}
self.registerOrderVM.getOrderPriceEstimation(orderInfo: self.orderPriceObject).asObservable().subscribe(onNext: { (response) in
if let res = response as? [String: Int], let p = res["price_with_added_value"] {
DispatchQueue.main.async {
self.customView?.setOrderPriceEstimate(price: "cost : \(p)")
}
}
}, onError: { (error) in
self.view.showMessage(error.localizedDescription, type: .error, options: [.hideOnTap(true)])
}).disposed(by: self.disposeBag)
}
}
verify if p exists or not
if let res = response as? [String: Int], let p = res["price_with_added_value"] {
DispatchQueue.main.async {
self.customView?.setOrderPriceEstimate(price: "cost : \(p)") }
}
else
{
print("res or p is not found")
}
Also check if customView is nil
I called data from the web for infinite-scrolling and "push to refresh", now infinite-scrolling work well, but "Pull to refresh" is not work because I do not know what kind of code I have to write in refreshAction func.
NetworkRequestAPI Request
import Foundation
class NetworkRequestAPI {
static func getPropductListByCategory(productId : Int, pageNo : Int , completion: #escaping ([Product]? , Error?) -> ()){
let url = URL(string: Configuration.BASE_URL+"/product-by/type?product_type_id="+String(productId)+"&page="+String(pageNo))
var categoryObject = [Product]()
URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in
if error != nil {
}
else {
do {
let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]
let products = json["products"] as? [String: Any]
// productCount = (json["product_count"] as? Int)!
let items = products?["data"] as? [[String:Any]]
items?.forEach { item in
let oProduct = Product()
oProduct.product_id = item["product_id"] as? Int
oProduct.product_name = item["product_name"] as? String
oProduct.product_image = item["product_image"] as? String
let ratingItem = item["rating_info"] as? [String: AnyObject]
let rating = RatingInfo()
rating.final_rating = ratingItem?["final_rating"] as? String
oProduct.rating_info = rating
categoryObject.append(oProduct)
}
completion(categoryObject, nil)
} catch let error as NSError {
print(error)
completion(nil, error)
}
}
}.resume()
}
}
ListTableView Class
class ListTableView: UITableViewController {
var isInitUILoad = true
var arrProduct = [[Product]]()
var product_id:Int = 0
var pageNo = 1
override func viewDidLoad() {
super.viewDidLoad()
self.initUILoad()
let refreshControl = UIRefreshControl()
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
refreshControl.addTarget(self, action: #selector(refreshWeatherData(_:)), for: .valueChanged)
}
#objc private func refreshWeatherData(_ sender: Any) {
//
// what codes have to add here
//
self.refreshControl?.endRefreshing()
}
func initUILoad(){
ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)
NetworkRequestAPI.getPropductListByCategory(productId: product_id, pageNo: pageNo) { (products, error) in
DispatchQueue.main.async(execute: {
if products != nil {
// self.totalItemLabel.text = String(self.product_count) + " products"
self.pageNo += 1
// self.product_count = productCount
//self.arrProduct = products!
self.arrProduct.append(products!)
print(self.arrProduct.count)
// self.tableView?.reloadData()
}else{
print(error.debugDescription)
}
ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
// self.totalItemLabel.text = String(self.product_count) + " products"
self.tableView?.reloadData()
self.isInitUILoad = false
})
}
}
func loadMore(complition:#escaping (Bool) -> ()) {
NetworkRequestAPI.getPropductListByCategory(productId: product_id, pageNo: pageNo) { (products, error) in
DispatchQueue.main.async(execute: {
if error != nil{
print(error.debugDescription)
}
if products != nil && products?.count ?? 0 > 0{
// self.totalItemLabel.text = String(self.product_count) + " products"
self.pageNo += 1
// self.product_count = productCount
// self.arrProduct = products!
self.arrProduct.append(products!)
self.tableView?.insertSections([self.arrProduct.count - 1], with: .fade)
// self.tableView?.reloadData()
}else{
print("no product left")
}
complition(true)
})
}
}
}
#objc private func refreshWeatherData(_ sender: Any) {
NetworkRequestAPI.getPropductListByCategory(productId: product_id, pageNo: 1) { (products, error) in
DispatchQueue.main.async(execute: {
if products != nil {
// self.totalItemLabel.text = String(self.product_count) + " products"
self.arrProduct = products!
print(self.arrProduct.count)
}else{
print(error.debugDescription)
}
self.refreshControl?.endRefreshing()
// self.totalItemLabel.text = String(self.product_count) + " products"
self.tableView?.reloadData()
self.isInitUILoad = false
})
}
}
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()
}
}