In filter selection view controller i will select the brands and then when i press apply it will pop to another screen and if the user to come back again to same page the previously selected should have check mark and that should save temporarily until the user leaves from filter page to list page
func downloadJsonWithURL() {
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
self.products = jsonObj.map{ Product(dict: $0) }
DispatchQueue.main.async {
self.tableDetails.reloadData()
}
}
} catch {
print(error)
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "filterSelectionCell", for: indexPath) as! FilterSelectionCell
activityIndicator.stopAnimating()
activityIndicator.hidesWhenStopped = true
tableDetails.isHidden = false
let product = products[indexPath.row]
cell.brandProductName.text = product.name
cell.accessoryType = product.selected ? .checkmark : .none
if namesArray.count != 0 {
for name in namesArray{
if product.name.contains(name){
print(product.name)
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selected = products[indexPath.row].selected
products[indexPath.row].selected = !selected
tableView.reloadRows(at: [indexPath], with: .none)
let selectedItems = products.filter{ $0.selected }
let selectedNames = products.filter{ $0.selected }.map{ $0.name }
let cell = tableView.cellForRow(at: indexPath)
selectedIndexPathArray.append(indexPath as NSIndexPath)
}
struct Product {
let name : String
let value : String
let img : String
let id : Int
var selected = false
init(dict : [String:Any]) {
self.name = dict["name"] as? String ?? ""
self.value = dict["value"] as? String ?? ""
self.img = dict["img"] as? String ?? ""
self.id = dict["id"] as? Int ?? 0
}
}
Related
I have home collectionView, here if i click one item using didSelectItemAtindexPathin in home that item values array need to show in AllMakePaymentViewController tableview.
but here i am getting all home items values in AllMakePaymentViewController... but how to show only clicked item values in AllMakePaymentViewController tableview.
for that same typename have in both home and AllMakePaymentViewController json..
Please help me in the code.
here is my code for homeVC:
import UIKit
import SDWebImage
struct JsonData {
var iconHome: String?
var typeName: String?
var id: String?
init(icon: String, tpe: String, id: String) {
self.iconHome = icon
self.typeName = tpe
self.id = id
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var typeName: String?
var saveTypenameKey: String?
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
cell.paymentImage.sd_setImage(with: URL(string:aData.iconHome ?? ""), placeholderImage: UIImage(named: "varun finance5_icon"))
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if itemsArray[indexPath.item].typeName == "WATER"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "ELECTRICITY"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "CASH POINT"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else if itemsArray[indexPath.item].typeName == "DTH"{
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
self.navigationController?.pushViewController(nextViewController!, animated: true)
}
else{
AlertFun.ShowAlert(title: "", message: "will update soon..", in: self)
}
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.com/webservices/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
//print("the home json is \(jsonObj)")
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as? String
let pic = financer["icon"] as? String
self.typeName = financer["tpe"] as! String
KeychainWrapper.standard.set(self.typeName!, forKey: "typeName")
print("keychain typename \(KeychainWrapper.standard.set(self.typeName!, forKey: "typeName"))")
self.itemsArray.append(JsonData(icon: pic ?? "", tpe: self.typeName ?? "", id: id ?? ""))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
This is my AllMakePaymentViewController code:
class PaymentTableViewCell: UITableViewCell{
#IBOutlet weak var pamntTypeLabel: UILabel!
}
class AllMakePaymentViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var categoryName: String?
var iteamsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
allPaymentService()
}
func allPaymentService(){
let urlStr = "https://dev.com/webservices/api.php?rquest=billermdm"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
//print("the all make payment json is \(jsonObj)")
let billerdetailsArray = jsonObj["billerdetails"] as! [[String: Any]]
for billerdetail in billerdetailsArray {
self.categoryName = billerdetail["bcategoryname"] as? String
if self.categoryName == "Water"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "Electricity"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "CashPoin"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
if self.categoryName == "DTH"{
let bName = billerdetail["bname"] as? String
self.iteamsArray.append(bName ?? "")
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
extension AllMakePaymentViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if categoryName == "Water"{
return iteamsArray.count
}
if categoryName == "Landline Postpaid"{
return iteamsArray.count
}
if categoryName == "DTH"{
return iteamsArray.count
}
if categoryName == "Electricity"{
return iteamsArray.count
}
return iteamsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell
cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
self.tableView.separatorStyle = .none
return cell
}
}
here only one itemsArray is enough or shall i take diierent array fro different category like electrictyArray, waterArray... because here i am getting all values in tabelview... i need only clicked home item valuesarray..
Please help me in the code
You need to set the var in nextViewController before pushing it onto the stack (and you should use if let to avoid potential crashes):
if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController {
// set the var in the new view controller
nextViewController.categoryName = "WATER"
// now push it onto the stack
self.navigationController?.pushViewController(nextViewController, animated: true)
}
I am pushing data which is an array of strings to a tableview controller. These strings are "uid's" which are users in my database. With this array I make a call to firebase to extract all users and then do a match to the uid's. I am getting the correct data, yet I print out everything to make sure when the data is available and the data is available only after the tableview cell loads which causes the data to be nil causing a crash or just empty data. How can I make the data load first and then the cell so the data is available for display?
I've created functions for the data and now I have it in my viewDidLoad. Also, you'll see I have tried adding the firebase call into the Cell setup but of course that does not work.
Array of strings
var data = [String]()
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessDictionary = customerValue as! NSDictionary
print(self.businessDictionary)
print("Just printed the business dictionary")
}
}
}
}
} else {
print("does not exist")
}
})
}
Tableview Cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
print(self.businessDictionary)
print("Print the dictionary here to check the values")
let businessValues = self.businessDictionary
let uid = self.data.description
print(businessValues)
print("printed the business values")
if let dict = businessValues {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessData = customerValue as? NSDictionary
print(self.businessData)
print("Printing matching the uid values")
}
}
}
}
cell.businessName.text = businessData?["businessName"] as? String
cell.businessStreet.text = businessData?["businessStreet"] as? String
cell.businessCity.text = businessData?["businessCity"] as? String
cell.businessState.text = businessData?["businessState"] as? String
let businessProfilePicture = businessData?["profPicString"] as? String
if (businessProfilePicture!.characters.count) > 0 {
let url = URL(string: (businessProfilePicture!))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}
Here is my solution. Got it to work. Appened and used "usersArray" to get and display the data.
var data = [String]()
var usersArray = [NSDictionary?]()
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.usersArray.append(customerValue as! NSDictionary)
self.followUsersTableView.reloadData()
}
}
}
}
} else {
print("does not exist")
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.usersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
let user : NSDictionary?
user = self.usersArray[indexPath.row]
cell.businessName.text = String(user?["businessName"] as! String)
cell.businessStreet.text = String(user?["businessStreet"] as! String)
cell.businessCity.text = String(user?["businessCity"] as! String)
cell.businessState.text = String(user?["businessState"] as! String)
let businessProfilePicture = String(user?["profPicString"] as! String)
if (businessProfilePicture.characters.count) > 0 {
let url = URL(string: (businessProfilePicture))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}
I parse JSON file, than I create new objects in Core Data managed context. At this point everything is ok, I get all valid objects. But when I try to renew data at tableView using NSFetchedResultsControllerDelegate method something goes wrong- NSFetchedResultsController returns the same object for 2 different index path. Moreover, if I try to catch the problem with breakpoints, 1 time at 3 NSFetchedResultsController start return valid objects. It's a bug of Core Data or else?
EDIT
Parsing JSON and save to Core Data:
private func performRequest(withURL url: URL) {
Alamofire.request(url).responseJSON(completionHandler: { (response) in
guard let result = response.result.value as? [String: Any] else {
return
}
DispatchQueue.main.async {
self.deleteAllPreviousData()
self.processResponse(result)
self.coreDataStack.saveContext()
}
})
}
private func deleteAllPreviousData() {
let fetchCity = NSFetchRequest<NSFetchRequestResult>(entityName: "City")
let fetchWeather = NSFetchRequest<NSFetchRequestResult>(entityName: "Weather")
let requestCityDelete = NSBatchDeleteRequest(fetchRequest: fetchCity)
requestCityDelete.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
let requestWeatherDelete = NSBatchDeleteRequest(fetchRequest: fetchWeather)
requestWeatherDelete.affectedStores = coreDataStack.managedContext.persistentStoreCoordinator?.persistentStores
do {
try coreDataStack.managedContext.execute(requestWeatherDelete)
try coreDataStack.managedContext.execute(requestCityDelete)
} catch let error as NSError {
print("Delete fetching error: \(error), \(error.userInfo)")
}
}
private func processResponse(_ dictionary: [String: Any]) {
guard let cityList = dictionary["list"] as? [Any] else {
return
}
let newUpdateDate = Date()
for (id, city) in cityList.enumerated() {
//parse data from JSON
guard let city = city as? [String: Any] else {
return
}
let name = city["name"] as? String ?? ""
//FIXME: For debug
print(name)
guard let coordinates = city["coord"] as? [String: Any] else {
return
}
let lat = coordinates["lat"] as? Double ?? 0.0
let lon = coordinates["lon"] as? Double ?? 0.0
guard let main = city["main"] as? [String:Any] else {
return
}
let temperature = main["temp"] as? Int ?? 0
guard let weather = city["weather"] as? [Any] else { return }
guard let firstWeatherDescriptor = weather.first as? [String: Any] else { return }
let condition = firstWeatherDescriptor["main"] as? String ?? ""
let description = firstWeatherDescriptor["description"] as? String ?? ""
let iconName = firstWeatherDescriptor["icon"] as? String ?? "default_weather"
let newCity = City(context: coreDataStack.managedContext)
newCity.name = name
newCity.id = Int16(id)
newCity.renewData = newUpdateDate as NSDate
newCity.latitude = lat
newCity.longtitude = lon
let newWeather = Weather(context: coreDataStack.managedContext)
newWeather.city = newCity
newWeather.temperature = Int32(temperature)
newWeather.condition = condition
newWeather.conditionDescription = description
newWeather.iconName = iconName
}
}
Read data from Core Data
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//if no data was previous downloaded, than show Loading cell
if tableView.numberOfRows(inSection: 0) == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: updatingCellIdentifier, for: indexPath)
getLocation()
return cell
}
//FIXME: For debug
print("****")
print(indexPath)
print("****")
if indexPath.row == 0 {
return configureThisCityCell(at: indexPath)
} else {
return configureLocalCityCell(at: indexPath)
}
}
private func configureThisCityCell(at indexPath: IndexPath) -> CurrentCityTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: currentCityCellIdentifier, for: indexPath) as! CurrentCityTableViewCell
//TODO: configure cell
let currentCity = fetchedResultController.object(at: indexPath)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
cell.statusLabel.text = String(format: "Update at: %#", dateFormatter.string(from: currentCity.renewData! as Date))
cell.cityNameLabel.text = currentCity.name ?? NSLocalizedString("Unnown", comment: "Unnown city description")
cell.tempLabel.text = "\(String(describing: currentCity.weather!.temperature))°C"
cell.weatherDescriptionLabel.text = currentCity.weather?.conditionDescription
guard let conditionIconName = currentCity.weather?.iconName else { return cell }
guard let conditionIcon = UIImage(named: conditionIconName) else { return cell }
cell.weatherIconView.image = conditionIcon
return cell
}
private func configureLocalCityCell(at indexPath: IndexPath) -> LocalCityTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: localCityCellIdentifier, for: indexPath) as! LocalCityTableViewCell
//TODO: configure cell
let currentCity = fetchedResultController.object(at: indexPath)
//FIXME: For debug
print(indexPath)
print(currentCity.name)
print(currentCity.id)
print("__________")
cell.cityNameLabel.text = currentCity.name ?? NSLocalizedString("Unnown", comment: "Unnown city description")
cell.tempLabel.text = "\(String(describing: currentCity.weather!.temperature))°C"
cell.weatherDescriptionLabel.text = currentCity.weather?.conditionDescription
guard let conditionIconName = currentCity.weather?.iconName else { return cell }
guard let conditionIcon = UIImage(named: conditionIconName) else { return cell }
cell.weatherIconView.image = conditionIcon
return cell
}
extension CurrentWeatherTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
//TODO: this is works, but it is not solution, it's for time
do {
try controller.performFetch()
} catch let error as NSError {
print("Update error: \(error), \(error.userInfo)")
}
self.tableView.reloadData()
}
}
I had completed upto the create a new address but later on I don't have any idea how to implement as shown in image and later I try to get the arrays by using the code shown below but unable to print there if possible how to implement the code as shown in image and all the data presented in the image is of dynamic but I had placed some cells designed in storyboard and got into separate sections like images and buttons and after I got stuck here and the data I need to pass here is
{
"Flat": [
{
"price": "$5.00",
"id": 11,
"name": "Fixed"
}
],
"United Parcel Service": [
{
"price": "$109.12",
"id": 1,
"name": "worldwide Expedited"
},
{
"price": "$120.18",
"id": 2,
"name": "worldwide Express saver"
}
]
}
any help would be of great appreciation
func shippingaddressURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
self.detailsArray = (jsonObj!.value(forKey: "address") as? [[String: AnyObject]])!
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
func shippingmethodURL() {
let url = NSURL(string: self.urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
let arrayss = jsonObj?.allKeys
self.shippingArray = (jsonObj!.value(forKey: "Flat") as? [[String: AnyObject]])!
self.methodArray = (jsonObj!.value(forKey: "United Parcel Service") as? [[String: AnyObject]])!
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
func numberOfSections(in tableView: UITableView) -> Int{
// #warning Incomplete implementation, return the number of sections
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0){
return 1
}
else if (section == 1){
return detailsArray.count
}else if (section == 2){
return 1
}else if (section == 3) {
print(arrayss)
return arrayss.count
}else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "imagecell", for: indexPath) as! imageTableViewCell
return cell
}else if indexPath.section == 1{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! addressTableViewCell
tableDetails.isHidden = false
myActivityIndicator.stopAnimating()
let arr = detailsArray[indexPath.row]
cell.deleteButton.tag = indexPath.row
cell.nameLabel.text = arr["name"]as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Int = arr["number"] as! Int
// let checkIndex = arr["default"] as! Int
cell.mobileNumberLabel.text = String(describing: mobilenumber)
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}else{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
return cell
}else if indexPath.section == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! newAddressTableViewCell
return cell
}else if indexPath.section == 3{
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingmethodcell", for: indexPath) as! shippingMethodTableViewCell
// print(arrayss)
cell.methodLabel.text = arrayss[indexPath.row]
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "continuecell", for: indexPath) as! continueTableViewCell
return cell
}
}
Here is sample you want, hope it help.
class MyTableTableViewController: UITableViewController {
struct ShipPrice {
let title: String
let name: String?
let price: String?
let id: Int?
}
var datas: [ShipPrice] = {
guard let path = Bundle.main.path(forResource: "content2", ofType: nil) else {
fatalError("File not found.")
}
guard let content = try? String(contentsOfFile: path) else {
fatalError("Open content failed.")
}
guard let data = content.data(using: .utf8) else {
fatalError("Making data fialed.")
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else {
fatalError("JSON Serializetion failed.")
}
let parse: (String, [[String: Any]])->([ShipPrice]) = { title, datas in
var shipPrices = [ShipPrice]()
for data in datas {
guard let id = data["id"] as? Int, let name = data["name"] as? String, let price = data["price"] as? String else {
fatalError("Data key not found.")
}
let shipPrice = ShipPrice(title: title, name: name, price: price, id: id)
shipPrices.append(shipPrice)
}
return shipPrices
}
var shipPrices = [ShipPrice]()
if let datas = json as? [String: Any] {
if let flats = datas["Flat"] as? [[String: Any]] {
shipPrices.append(ShipPrice(title: "Flat", name: nil, price: nil, id: nil))
shipPrices.append(contentsOf: parse("Flat", flats))
}
if let uPS = datas["United Parcel Service"] as? [[String: Any]] {
shipPrices.append(ShipPrice(title: "United Parcel Service", name: nil, price: nil, id: nil))
shipPrices.append(contentsOf: parse("United Parcel Service", uPS))
}
}
return shipPrices
}()
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return datas.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if datas[indexPath.row].name == nil && datas[indexPath.row].price == nil {
cell = tableView.dequeueReusableCell(withIdentifier: "cell_1", for: indexPath)
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
cell.textLabel?.text = datas[indexPath.row].title
}
else {
cell = tableView.dequeueReusableCell(withIdentifier: "cell_2", for: indexPath)
cell.textLabel?.text = datas[indexPath.row].name! + datas[indexPath.row].price!
}
return cell
}
}
i am having webservices data as shown below in the shipping method
{
"Flat": [
{
"price": "$5.00",
"id": 11,
"name": "Fixed"
}
],
"United Parcel Service": [
{
"price": "$109.12",
"id": 1,
"name": "worldwide Expedited"
},
{
"price": "$120.18",
"id": 2,
"name": "worldwide Express saver"
}
]
}
i need to pass this data to the table view as shown below can anyone help me how to implement this in table view dynamically that is flat and united parcel service both are dynamic and inside arrays also dynamic can anyone help me how to pass the data to table view to display as shown in image and my code is shown below
func shippingaddressURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
self.shippingArray = (jsonObj!.value(forKey: "address") as? [[String: AnyObject]])!
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
func assignValuesToObjecs(arrayvalues: NSArray){
(arrayvalues as NSArray).enumerateObjects({ (object, count, stop) in
let Object :shippingObject = shippingObject()
Object.name = (object as AnyObject) .value(forKey: "name") as! String
Object.id = (object as AnyObject) .value(forKey: "id") as! NSInteger
Object.price = (object as AnyObject).value(forKey: "price")as! String
self.detailsArray.append(Object)
})
}
func shippingmethodURL() {
let url = NSURL(string: self.urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary { print(jsonObj!)
self.arrayss = (jsonObj?.allKeys)! as! [String]
//self.shippingArray = (jsonObj!.value(forKey: "Flat") as? [[String: AnyObject]])!
self.assignValuesToObjecs(arrayvalues :(jsonObj?["Flat"] as? [[String: AnyObject]]! as? NSArray)!)
self.assignValuesToObjecs(arrayvalues :(jsonObj?["United Parcel Service"] as? [[String: AnyObject]]! as? NSArray)!)
self.methodArray = (jsonObj!.value(forKey: "United Parcel Service") as? [[String: AnyObject]])!
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
#IBAction func selectRadioButton(_ sender: KGRadioButton) {
let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
_ = self.checkIsButtonEnable.index(of: sender.tag)
if sender.isSelected {
} else{
if(chekIndex == nil){
self.checkIsRadioSelect.removeAll(keepingCapacity: false)
self.checkIsRadioSelect.append(sender.tag)
self.checkIsButtonEnable.removeAll(keepingCapacity: false)
self.checkIsButtonEnable.append(sender.tag)
self.tableDetails.reloadData()
}
}
}
func numberOfSections(in tableView: UITableView) -> Int{
// #warning Incomplete implementation, return the number of sections
return 5
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "SHIPPING ADDRESS"
}
else if section == 2{
return "SHIPPING METHOD"
}
else{
return ""
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.darkGray
header.textLabel?.textAlignment = NSTextAlignment.center
header.textLabel?.font = UIFont(name: "Futura", size: 17)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0){
return shippingArray.count
}else if (section == 1){
return 1
}else if (section == 2) {
return arrayss.count
}else if (section == 3){
return detailsArray.count
}
else {
return 1
}
}
#IBAction func deleteAction(_ sender: UIButton) {
shippingArray.remove(at:sender.tag)
self.tableDetails.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! addressTableViewCell
tableDetails.isHidden = false
myActivityIndicator.stopAnimating()
let arr = shippingArray[indexPath.row]
cell.deleteButton.tag = indexPath.row
cell.nameLabel.text = arr["name"] as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Int = arr["number"] as! Int
cell.mobileNumberLabel.text = String(describing: mobilenumber)
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}else{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
return cell
}else if indexPath.section == 1{
let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! newAddressTableViewCell
return cell
}
else if indexPath.section == 2{
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingcell", for: indexPath) as! shippingMethodTableViewCell
cell.methodLabel.text = arrayss[indexPath.row]
return cell
}
else if indexPath.section == 3{
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingTypeCell", for: indexPath) as! shippingMethodTypeTableViewCell
var Object : shippingObject = shippingObject()
Object = detailsArray[indexPath.row]
cell.nameLabel.text = Object.name
cell.priceLabel.text = Object.price
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "continuecell", for: indexPath) as! continueTableViewCell
return cell
}
}
Any help would be of great appreciation