ObjectMapper displayed model in TableView Swift - ios

I am new to Swift , i parsing my JSON by using ObjectMapper but I want data displayed in TableView
I do not know how to do that
My Model:
import Foundation
import ObjectMapper
import SwiftyJSON
class AllCnannelModel : Mappable {
var id : Int?
var name: String?
var url : URL?
var picture : URL?
var category_id: Int?
required init?(map: Map) {}
func mapping(map: Map) {
id<-map["id"]
name<-map["name"]
url<-map["url"]
picture<-map["picture"]
category_id<-map["category_id"]
}
}
My TableView :
var name = [String]()
var urlChannel = [URL]()
override func viewDidLoad() {
super.viewDidLoad()
let URL = "http://52.50.138.211:8080/ChanelAPI/chanels"
Alamofire.request(URL).responseArray { (response: DataResponse<[AllCnannelModel]>) in
let channnellArray = response.result.value
if let channnellArray = channnellArray {
for channel in channnellArray {
self.name.append(channel.name!)
}
}
self.tableView.reloadData()
}
}
I can describe one type of data in the array and display:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.name.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = self.name[indexPath.row]
return cell
}
but i want all type of data in one array and display TableViewController
How can you implement?

Did you implemented numberOfSections(in tableView: UITableView) -> Int ?

Related

Use Realm Query Results as UITableView Section Headers

I am trying to use results from a Realm query as section headers in a UITableView.
Realm classes:
class Person: Object {
#objc dynamic var personId = UUID().uuidString
#objc dynamic var firstName: String = ""
#objc dynamic var surname: String = ""
#objc dynamic var mobileNumber: Int = 0
#objc dynamic var password: String = ""
override static func primaryKey() -> String? {
return "personId"
}
}
class Category: Object {
#objc dynamic var categoryId = UUID().uuidString
#objc dynamic var person: Person?
#objc dynamic var categoryName: String = ""
let categoryContent = List<String>()
override static func primaryKey() -> String? {
return "categoryId"
}
}
My code:
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let realm = try! Realm()
var itemsInSections: Array<Array<String>> = [["1A"], ["2A"], ["3A"], ["4A"], ["5A"], ["6A"], ["7A"], ["8A"], ["9A"], ["10A"]] //Test content to figure out later
#IBOutlet weak var tableDetails: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableDetails.dataSource = self
tableDetails.delegate = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return getCategoryNames().count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsInSections[section].count
}
private func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> [String] {
return getCategoryNames()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath)
let text = self.itemsInSections[indexPath.section][indexPath.row]
cell.textLabel!.text = text
return cell
}
func getCategoryNames() -> [String] {
let categoryNames = realm.objects(Category.self).filter("person.mobileNumber == %#", mobileNumber).map({$0.categoryName})
return Array(categoryNames)
}
}
The number of sections works perfectly, but the section headers are blank.
If I add:
print(Array(categoryNames))
to the getCategoryNames function, it returns ["Category 1", "Category 2", "Category 3", "Category 4"] several times. This seems to be the correct format for the string that is required for the section headers, but the table header is not showing.
Try this:
private func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let nameArr = getCategoryNames()
return nameArr[section]
}
Function: func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? so you need to return string for a particular section.

How to get the name list on Realm database and display on my stimulator?

Here I have a Realm Database which is have some data in it and I want to display it on my Stimulator but it turn out display some other thing. What's wrong in my code?
This is the data of my Realm Database and I also marked the data which I want to display it.
The stimulator which display something like this.
And here is my ViewController.swift code's.
import UIKit
import RealmSwift
class ViewController: UIViewController,UITableViewDataSource { //UITableViewDataSource
#IBOutlet weak var mytableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
return theItem.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
print(theItem)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
//I suspect the problem is at here...
cell?.textLabel?.text = "\(theItem)"
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
class Category: Object {
#objc dynamic var name: String?
#objc dynamic var caid: Int = 0
}
class Item: Object {
#objc dynamic var name: String?
#objc dynamic var itemid: Int = 0
#objc dynamic var cateid: Int = 0
}
Your problem is that you need to get the string from the Item object. try something like
"\(theItem.name)".
func getNames() -> [String]{
let items = realm.objects(Item.self).filter("itemid >= 1").toArray(ofType: Item.self ) as [Item]
return items.map { $0.name }
}
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
I found a way to display the data already. I just need to add indexPath.row in my code and it can handle the data already.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
//I only add below this indexpath
let cellData = theItem[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
//and change this part and it's done.
cell?.textLabel?.text = cellData.name
print(theItem)
return cell!
}

Convert JSON to a Array with struct

I am trying to make a IOS app that is a home automation thing. I am using TableViewCell to display information.
My problem is that I have no idea how to get JSON to an Array with struct because I have to have struct I think.
My JSON is:
[{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}]
My code is:
struct cellData {
let nameLabel : String!
let stateLabel : String!
}
class Main: UITableViewController {
var array = [cellData]()
override func viewDidLoad() {
array = [cellData(nameLabel: "tv", stateLabel: "up_tv"),
cellData(nameLabel: "tv", stateLabel: "down_tv")]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.nameLabel.text = array[indexPath.row].nameLabel
cell.stateLabal.text = array[indexPath.row].stateLabel
return cell
}
You need jsonDecoder
struct cellData : Decodable {
let nameLabel : String
let stateLabel : String
enum CodingKeys:String,CodingKey {
case nameLabel = "namea"
case stateLabel = "statea"
}
}
//
let str = """
[{"namea":"TV","statea":"up_tv"},{"namea":"test","statea":"test"}]
"""
do {
let cellArr = try JSONDecoder().decode([cellData].self, from: str.data(using:.utf8)!)
print(cellArr) //// check this
} catch {
}
//
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as TableViewCell
}

tableView Cell not displaying data, What's the issue? (Swift 3)

So I have a view controller that is parsing some bitcoin price data. The function successfully responds and parses the data, but I cannot seem to get it to display in tableView.
I have already tested the outlets and identities via a test cell, which does work.
What am I doing wrong?
Code: `
import UIKit
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
class Response: Mappable{
var data: [Amount]?
required init?(map: Map){
}
func mapping(map: Map) {
data <- map["data"]
}
}
class Amount: Mappable {
var data : String?
required init?(map: Map){
}
func mapping(map: Map) {
data <- map["data.amount"]
}
}
class ViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
var mount = [String]()
var am = [String]()
#IBOutlet var tableView: UITableView!
func Call_bitcoin() {
let url = "https://api.coinbase.com/v2/prices/BTC-USD/buy"
Alamofire.request(url).responseObject{ (response: DataResponse<Amount>) in
let mount = response.result.value
let am = mount?.data
self.tableView.reloadData()
return
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
Call_bitcoin()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return am.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
print(am)
cell.textLabel?.text = am[indexPath.row]
return cell
}
}
`
You want to add elements in your Call_bitcoin() function but you are doing it wrong. You have already created var am = [String](). So you don't need to use let am = mount?.data. You could add your data in your am variable which is already created. You need to change some of your code lines in Call_bitcoin() function:
From:
let mount = response.result.value
let am = mount?.data
To:
let mount = response.result.value
am.append(mount?.data) // This part should be set by your 'mount?.data' value type
Your JSON not returning array, it's having dictionary.that why you get
am.count = 0
Solve first your data and put data into the array.
{"data":{"amount":"2414.88","currency":"USD"},"warnings":[{"id":"missing_version","message":"Please supply API version (YYYY-MM-DD) as CB-VERSION header","url":"https://developers.coinbase.com/api#versioning"}]}

Pass data from struct array to new tableview controller

I am trying to pass data from my Cheats struct into a new tableviewcontroller to populate the new table with the relevant info.
I have done research but am new to swift.
I do have experience in php but transferring my knowledge is proving quite difficult...
In my prepare for segue class i receive a few errors:
Definition conflicts with previous value:
var DataPass = CheatsArray[indexPath.row]
Cannot assign value type 'String' to '[String]':
DestViewController.CheatsArray = DataPass.name
Here is a copy of my current 3 files
Structs and arrays:
struct Game {
var name : String
var cheats : [Cheat]
}
struct Cheat {
var name : String
var code : String
var description : String
}
// Create Our Game Info And Cheats / Codes For Each Game!
//-------------------------------------------------------
let COD4 = Game(name: "Call Of Duty 4", cheats: [Cheat(name: "Cheat", code: "Code", description: "Description")])
let GTAV = Game(name: "Grand Theft Auto 5", cheats: [Cheat(name: "Cheat", code: "Code", description: "Description")])
// Place Our New Games Inside This Array!
//---------------------------------------
let ArrayOfGames = [COD4,GTAV]
GameListController:
import Foundation
import UIKit
class GamesListViewController: UITableViewController {
var CheatsArray = [Game]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ArrayOfGames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = ArrayOfGames[indexPath.row].name
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
let DestViewController = segue.destinationViewController as! CheatsListViewController
let DataPass : Game
var DataPass = CheatsArray[indexPath.row]
DestViewController.CheatsArray = DataPass.name
}
}
CheatListController:
class CheatsListViewController: UITableViewController {
var CheatsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CheatsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)
cell.textLabel?.text = CheatsArray[indexPath.row]
return cell
}
}
The first error is because you defined DataPass twice, one row after another. You can't do that in the same scope. Change the name of one.
The second error is because you cannot assign value type 'String' to '[String]'. Just looking at CheatsArray and name variables, it's clear the first is an array and the second is most likely a string. You might want to append the name to the array.

Resources