How to fetch data from struct to TableView? - ios

So I'm doing Valorant App, I created my structs, but I couldn't figure out how to show this data in tableView. I created all characters for showing but i cant figure out how can i do that.
This is my struct one.
import Foundation
struct Agent: Hashable{
let name: String
let type: AgentType
let origin: String
let abilities: [String]
// let iconAgent : [UIImage]
}
enum AgentType:String{
case controller = "Controller"
case sentinel = "Sentinel"
case initiator = "Initiator"
case duelist = "Duelist"
}
This is my character generating struct.
struct ValorantReferenceApp {
var agents: [Agent] = [
Agent(name: "Brimstone", type: .controller, origin: "United States", abilities: [ "Incendiary",
"Stim Beacon",
"Sky Smoke",
"Orbital Strike"]),
Agent(name: "Viper", type: .controller, origin: "United States", abilities: ["Snake Bite",
"Poison Cloud",
"Toxic Screen",
"Viper's Pit"]),
Agent(name: "Omen", type: .controller, origin: "Unknown", abilities: [
"Shrouded Step",
"Paranoia",
"DarkCover",
"FromtheShadows"]),
Agent(name: "Killjoy", type: .sentinel, origin: "Germany", abilities: ["Alarmbot",
"Nanoswarm",
"Turret",
"Lockdown"]),
Agent(name: "Cypher", type: .sentinel, origin: "Morocco", abilities: ["Trapwire",
"Cyber Cage",
"Spycam",
"Neural Theft"]),
Agent(name: "Sova", type: .initiator, origin: "Russia", abilities: ["Owl Drone",
"Shock Bolt",
"Recon Bolt",
"Hunter's Fury"]),
Agent(name: "Sage", type: .sentinel, origin: "China", abilities: ["Barrier Orb",
"Slow Orb",
"Healing Orb",
"Resurrection"]),
Agent(name: "Phoenix", type: .duelist, origin: "United Kingdom", abilities: ["Blaze",
"Curveball",
"HotHands",
"Runit Back"]),
Agent(name: "Jett", type: .duelist, origin: "South Korea", abilities: ["Cloudburst",
"Updraft",
"Tailwind",
"Blade Storm"]),
Agent(name: "Reyna", type: .duelist, origin: "Mexico", abilities: ["Leer",
"Devour",
"Dismiss",
"Empress"]),
Agent(name: "Raze", type: .duelist, origin: "Brazil", abilities: ["Boom Bot",
"Blast Pack",
"Paint Shells",
"Showstopper"]),
Agent(name: "Breach", type: .initiator, origin: "Sweden", abilities:
["Aftershock",
"Flashpoint",
"FaultLine",
"Rolling Thunder"]),
Agent(name: "Skye", type: .initiator, origin: "Australia", abilities: ["Regrowth",
"Trailblazer",
" GuidingLight",
"Seekers"]),
Agent(name: "Yoru", type: .duelist, origin: "Japan", abilities: ["Fakeout",
"Blindside",
"Gatecrash",
"Dimensional Drift"]),
Agent(name: "Astra", type: .controller, origin: "Ghana", abilities: [
"GravityWell",
"Nova Pulse",
"Nebula/Dissipate",
"Astral Form"]),
Agent(name: "KAYO", type: .initiator, origin: "AT Earth", abilities: ["FRAG/ment",
"FLASH/drive",
"ZERO/point",
"NULL/cmd"]),
Agent(name: "Chamber", type: .sentinel, origin: "France", abilities: ["Trademark",
"Headhunter",
"Rendezvous",
"Tour De Force"]),
Agent(name: "Neon", type: .duelist, origin: "Philippines", abilities: ["FastLane",
"RelayBolt",
"HighGear",
"Overdrive"]),
Agent(name: "Fade", type: .initiator, origin: "Turkey", abilities: ["Prowler",
"Seize",
"Haunt",
"Nightfall"])
]
}
This im my TableView view controller.
import UIKit
class AgentListVC: UIViewController {
var agentsReference = ValorantReferenceApp().agents
var agentProperties : Agent?
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
super.viewDidLoad()
}
}
extension AgentListVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return agentsReference.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! AgentCellVC
// cell.agentNameLAbel.text = agentProperties?.name
return cell
}
}
I simply want to reflect the name property as text in the tableView, but I cannot access the name and other properties in my structs. How can i do that?

You are really close :)
You already have the list of agents associated with your view controller, you just need to find the correct agent at the right index, you can do that like so:
let agent = agentsReference[indexPath.row]
cell.agentNameLAbel.text = agent.name

Related

getting only one item from decoding json response iOS

I've a response from MapBox API. I want to store each Feature object of features array in a array then want to display from that array to table view.
{
type: "FeatureCollection",
query: [
"u"
],
features: [{
id: "country.19678805456372290",
type: "Feature",
place_type: [
"country"
],
relevance: 1,
properties: {
wikidata: "Q30",
short_code: "us"
},
text: "United States",
place_name: "United States",
matching_text: "US",
matching_place_name: "US",
bbox: [
-179.9,
18.8163608007951,
-66.8847646185949,
71.4202919997506
],
center: [
-97.9222112121185,
39.3812661305678
],
geometry: {
type: "Point",
coordinates: [
-97.9222112121185,
39.3812661305678
]
}
},
{
id: "country.12405201072814600",
type: "Feature",
place_type: [
"country"
],
relevance: 1,
properties: {
wikidata: "Q145",
short_code: "gb"
},
text: "United Kingdom",
place_name: "United Kingdom",
bbox: [
-8.74974065661991,
49.802416901086,
1.86276379960989,
60.9093517989553
],
center: [
-2.36966957036279,
54.2379333607472
],
geometry: {
type: "Point",
coordinates: [
-2.36966957036279,
54.2379333607472
]
}
},
{
id: "country.11702916565595680",
type: "Feature",
place_type: [
"country"
],
relevance: 1,
properties: {
wikidata: "Q878",
short_code: "ae"
},
text: "United Arab Emirates",
place_name: "United Arab Emirates",
bbox: [
51.4160146192147,
22.6282410017159,
56.4814183948386,
26.094609499407
],
center: [
54.2561723713588,
23.8520599823879
],
geometry: {
type: "Point",
coordinates: [
54.2561723713588,
23.8520599823879
]
}
},
{
id: "country.11871993712476590",
type: "Feature",
place_type: [
"country"
],
relevance: 1,
properties: {
wikidata: "Q212",
short_code: "ua"
},
text: "Ukraine",
place_name: "Ukraine",
bbox: [
22.1375690033684,
44.3152913001972,
40.2255909904191,
52.3793529890401
],
center: [
31.3202829593814,
49.3227937844972
],
geometry: {
type: "Point",
coordinates: [
31.3202829593814,
49.3227937844972
]
}
},
{
id: "country.9140805109496660",
type: "Feature",
place_type: [
"country"
],
relevance: 1,
properties: {
wikidata: "Q77",
short_code: "uy"
},
text: "Uruguay",
place_name: "Uruguay",
matching_text: "URY",
matching_place_name: "URY",
bbox: [
-58.4891219951353,
-35.0552819973662,
-53.1014000735687,
-30.0855740544354
],
center: [
-56.012396238658,
-32.7996455126793
],
geometry: {
type: "Point",
coordinates: [
-56.012396238658,
-32.7996455126793
]
}
}
],
attribution: "NOTICE: © 2021 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."
}
So, I create a model like this -
struct Response: Codable {
var features: [Feature]
}
struct Feature: Codable {
var id: String!
var type: String?
var matching_place_name: String?
var place_name: String?
var geometry: Geometry
var center: [Double]
var properties: Properties
}
struct Geometry: Codable {
var type: String?
var coordinates: [Double]
}
struct Properties: Codable {
var address: String?
}
And Write this code -
var suggestedPlacenames: NSMutableArray = []
func doShowSuggestion(usersQuery: String) {
let urlString = "\(mapbox_api)\(usersQuery).json?access_token=\(mapbox_access_token)"
let url = URL(string: urlString)
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data, error == nil else {
print("Error in URLSeesion")
return
}
if let result = try? JSONDecoder().decode(Response.self, from: data) {
self.suggestedPlacenames.add(result)
print(self.suggestedPlacenames.count)
} else {}
But by this I always get 1 length from self.suggestedPlacenames whatever the length of the response in features. How can I get each features object separately in self.suggestedPlacenames?
In your code :
self.suggestedPlacenames.add(result)
You add only one element to your array.
You must append the an array.
// declare as an array of features
var suggestedPlacenames = [Feature]()
self.suggestedPlacenames.append(contentsOf: result.features)
or
self.suggestedPlacenames += result.features
You need to delcare
var allFeatures = [Feature]()
do {
let result = try JSONDecoder().decode(Response.self, from: data)
self.allFeatures = result.features
print(self.allFeatures.count)
}
catch {
print(error)
}
Then

Creating nested dictionary for JSON

I am trying to replicate the json format for a POST request, but I am having trouble working with the following 2D dictionary in Swift.
payload = {"cardholder": {
"address": {
"city": "city",
"state": "MA",
"street": "street",
"zip_code": "11111"
},
"shipping_address": {
"city": "city",
"state": "MA",
"street": "street",
"zip_code": "11111"
}
}}
Is there a way I can set up addressDetails and shippingDetails?
var addressDetails = ["city": self.newCity!, "state": self.newState!,"street": self.newStreet!,"zip_code": self.newZipcode!]
var shippingDetails = ["city": self.newCity!, "state": self.newState!,"street": self.newStreet!,"zip_code": self.newZipcode!]
if self.newUnit != ""{
addressDetails["unit"] = self.newUnit!
shippingDetails["unit"] = self.newUnit!
}
var test: [String:[String:[String:String]]] = ["cardholder": ["address": addressDetails]]
To answer your question: yes. Everything you need to do is add shippingDetails to the test["cardholder"] dict:
var test: [String:[String:[String:String]]] = ["cardholder": ["address": addressDetails, "shipping_address": shippingDetails]]
However, I totally agree with #Paulw11, you should not fiddle around with dictionaries that way. Use structs that conform to Codable instead:
struct Address: Codable {
var city: String
var state: String
var street: String
var zipCode: String
var unit: String?
enum CodingKeys: String, CodingKey {
case city, state, street, zipCode = "zip_code", unit
}
}
struct Cardholder: Codable {
var address: Address
var shippingAddress: Address
enum CodingKeys: String, CodingKey {
case address, shippingAddress = "shipping_address"
}
}
struct Payload: Codable {
var cardholder: Cardholder
}
...
let addressDetails = Address(city: self.newCity!, state: self.newState!, street: self.newStreet!, zipCode: self.newZipcode!, unit: self.newUnit == "" ? nil : self.newUnit)
let shippingDetails = Address(city: self.newCity!, state: self.newState!, street: self.newStreet!, zipCode: self.newZipcode!, unit: self.newUnit == "" ? nil : self.newUnit)
var test = Payload(cardholder: Cardholder(address: addressDetails, shippingAddress: shippingDetails))

How to get array in ascending order based on key value in Swift3 iOS

I am creating a database App in Swift3, where I have to display the data in UITableView from JSON. Below is my JSON :
{
"Success": 1,
"data": [{
"Session_Details": [{
"Start_Time": "08:00",
"End_Time": "10:00",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 2,
"Tag_Name": "Test 2",
"Tag_Order": 1
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 3,
"Tag_Name": "Test 3",
"Tag_Order": 3
}]
},
{
"Start_Time": "13:30",
"End_Time": "15:20",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
}
]
}]
}
I have already parsed the JSON and getting all the JSON data.
My problem is I have to create an array of 'Tag_Details' that should have unique value, It means Tag_Id should be unique. Also I have to set the array in ascending order based on Tag_Order key.
I am trying below code but not working :
var sessions : [SessionData]! {
return AgendaDataManager.sharedInstance.sessionData
}
let sortedResults = session.tagDetails!.sortedArray(using: [NSSortDescriptor(key: "tagOrder", ascending: true)])
let sessionTag = ((session.tagDetails as AnyObject).allObjects as! [TagData])[0]
Please suggest me. Thank you.
If you are coding in Swift 3 and can't work with Codable protocol
First you should structure your json data. You can use this helper quick type that will give a pretty good start point:
struct Root {
let success: Bool
let data: [Datum]
}
struct Datum {
let sessionDetails: [SessionDetail]
}
struct SessionDetail {
let startTime: String
let endTime: String
let tagDetails: [TagDetail]
}
struct TagDetail {
let tagId: Int
let tagName: String
let tagOrder: Int
}
Them you would need to create a custom initialiser for your root structure that takes a Data parameter (JSON Data):
typealias Dictionary = [String: Any]
typealias Dictionaries = [[String: Any]]
extension Root {
init?(_ data: Data) {
let dictionary = (try? JSONSerialization.jsonObject(with: data)) as? Dictionary ?? [:]
success = dictionary["Success"] as? Bool == true
guard success else {
return nil
}
self.data = (dictionary["data"] as! Dictionaries).map(Datum.init)
}
}
And initialisers that takes a dictionary for all structures.
extension Datum {
init(dictionary: [String: Any]) {
sessionDetails = (dictionary["Session_Details"] as! Dictionaries)
.map(SessionDetail.init)
}
}
extension SessionDetail {
init(dictionary: [String: Any]) {
startTime = dictionary["Start_Time"] as! String
endTime = dictionary["End_Time"] as! String
tagDetails = (dictionary["Tag_Details"] as! Dictionaries).map(TagDetail.init)
}
}
extension TagDetail: CustomStringConvertible {
init(dictionary: [String: Any]) {
tagId = dictionary["Tag_Id"] as! Int
tagName = dictionary["Tag_Name"] as! String
tagOrder = dictionary["Tag_Order"] as! Int
}
var description: String {
return "TagDetail(Id: \(tagId) - Name: \(tagName) - Order: \(tagOrder))"
}
}
Next you will need to make TagDetail conform to Equatable and Comparable:
extension TagDetail: Equatable, Comparable {
static func == (lhs: TagDetail, rhs: TagDetail) -> Bool {
return lhs.tagId == rhs.tagId
}
static func < (lhs: TagDetail, rhs: TagDetail) -> Bool {
return lhs.tagOrder < rhs.tagOrder
}
}
Once you accomplish all these steps you can easily filter and sort your objects:
let data = Data("""
{
"Success": 1,
"data": [{
"Session_Details": [{
"Start_Time": "08:00",
"End_Time": "10:00",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 2,
"Tag_Name": "Test 2",
"Tag_Order": 1
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 3,
"Tag_Name": "Test 3",
"Tag_Order": 3
}]
},
{
"Start_Time": "13:30",
"End_Time": "15:20",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
}
]
}]
}
""".utf8)
if let root = Root(data), root.success,
let sessionDetails = root.data.first?.sessionDetails {
for detail in sessionDetails {
print(detail)
}
let allTagDetails = sessionDetails.flatMap{$0.tagDetails}
let tagDetailsSorted = allTagDetails.sorted()
print("\n\n\n")
var set = Set<Int>()
let tagDetailsSortedSet = tagDetailsSorted.filter({ set.insert($0.tagId).inserted })
tagDetailsSortedSet.map{print($0)}
}
This will print
SessionDetail(startTime: "08:00", endTime: "10:00", tagDetails:
[TagDetail(Id: 1 - Name: Test 1 - Order: 4)])
SessionDetail(startTime:
"10:30", endTime: "12:30", tagDetails: [TagDetail(Id: 2 - Name: Test 2
- Order: 1)])
SessionDetail(startTime: "10:30", endTime: "12:30", tagDetails: [TagDetail(Id: 3 - Name: Test 3 - Order: 3)])
SessionDetail(startTime: "13:30", endTime: "15:20", tagDetails:
[TagDetail(Id: 1 - Name: Test 1 - Order: 4)])
and
TagDetail(Id: 2 - Name: Test 2 - Order: 1)
TagDetail(Id: 3 - Name: Test 3 - Order: 3)
TagDetail(Id: 1 - Name: Test 1 - Order: 4)

Did here existed a better solution to handle this api problem in Swift?

my raw json data maybe mislead you. The keys array were not always matched its value at the same index. So I rewrote my data to reflect my intentions.
Assume we have a table view to show songs with its json:
{
"albums": [
{
"title": "A",
"id": "174172",
"artistName": "Person X"
},
{
"title": "B",
"id": "19201827",
"artistName": "Person Y"
},
{
"title": "C",
"id": "1927",
"artistName": "Person Z"
}
],
"songs": [
{
"name": "Song A",
"albumName": "A",
"albumId": "174172",
"duration": 180
},
{
"name": "Song B",
"albumName": "A",
"albumId": "174172",
"duration": 200
},
{
"name": "Song C",
"albumName": "B",
"albumId": "19201827",
"duration": 216
},
{
"name": "Song D",
"albumName": "C",
"albumId": "1927",
"duration": 216
}
]
}
My schemas like this:
struct Album: Decodable {
let title: String
let id: String
let artistName: String
}
struct Song: Decodable {
let name: String
let albumName: String
let albumId: String
let duration: Int
}
The view controller fake code like this:
class ViewController: UIViewController {
var songs: [Song] = []
var albums: [Album] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell
let song = songs[indexPath.row]
let album = albums.first { $0.id == song.albumId }
cell.updateUI(withSong: song, album: album)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let song = songs[indexPath.row]
let album = albums.first { $0.id == song.albumId }
pushDetailSongViewController(song, album)
}
func pushDetailSongViewController(_ song: Song, _ album: Album?) {
}
}
When we have too many songs with albums, let album = albums.first { $0.id == song.albumId } is place with terrible performance problem.
So what data structure should we use here to handle updateing performance?
After parsing both keys and values, you could combine the two arrays to a dictionary and then have your table view's data source be that dictionary.
First, make your Song struct conform to the Hashable protocol:
struct Song: Hashable {
Create an array for both albums and songs:
var albums: [Album] = []
var songs: [Song] = []
Then, reduce the songs array to a dictionary as follows:
let data = songs.reduce([Album: Song]()) { (result, song) -> [Album: Song] in
guard let album = albums.first(where: { $0.id == song.albumID }) else { return result }
return result.merging([album: song], uniquingKeysWith: { (first, _) in first })
}
I tested this with two demo arrays:
let albums = [Album(id: "1", name: "one"), Album(id: "2", name: "two"), Album(id: "3", name: "three")]
let songs = [Song(albumID: "1", name: "ONE"), Song(albumID: "2", name: "TWO"), Song(albumID: "3", name: "THREE")]
Those turn data into:
[
<Album id: "1", name: "one"> : <Song albumID: "1", name: "ONE">,
<Album id: "2", name: "two"> : <Song albumID: "2", name: "TWO">,
<Album id: "3", name: "three">: <Song albumID: "3", name: "THREE">
]
Extra Credit
If you want all songs for each album, you have to make data [Album: [Song]]:
let data = albums.reduce([Album: [Song]]()) { (result, album) -> [Album: [Song]] in
let _songs = songs.filter({ $0.albumID == album.id })
guard !_songs.isEmpty else { return result }
return result.merging([album: _songs], uniquingKeysWith: { (first, _) in first })
}
With the following arrays:
let albums = [Album(id: "1", name: "one"), Album(id: "2", name: "two"), Album(id: "3", name: "three")]
let songs = [Song(albumID: "1", name: "ONE"), Song(albumID: "2", name: "TWO"), Song(albumID: "3", name: "THREE"),
Song(albumID: "1", name: "ONE-1"), Song(albumID: "1", name: "ONE-2"), Song(albumID: "3", name: "THREE-1")]
...you will get:
[
<Album name: three, id: 3>: [
<Song name: THREE, albumID: 3>
<Song name: THREE-1, albumID: 3>
],
<Album name: one, id: 1>: [
<Song name: ONE, albumID: 1>,
<Song name: ONE-1, albumID: 1>,
<Song name: ONE-2, albumID: 1>
],
<Album name: two, id: 2>: [
<Song name: TWO, albumID: 2>
]
]
You should create a struct like below after the JSON parsing has been completed.
struct DataSet {
let id: String
let name: String
let value: String
}
Moreover looking at your json, it seems like objects at same index of Key and Value arrays are same with respect to id and key . So, at the time of combining both the arrays, if you iterate one array, you will be knowing the index of another array (O(1)) . Hence time complexity of merging will be O(n).
If you don't want to change too much, maybe a mapDictionary will help:
let keyMaps = [String : String](uniqueKeysWithValues: keys.map{($0.id, $0.name)})
keyNamesInSequenceSameWithValues = values.map{ keyMaps[$0.key]! )

Search in Mapped JSON

I need to implement search within this JSON, I've tried to do it but it's giving me error. Below is my code and Modal Class which I've mapped.
After trying every possible way, I still cannot resolve this error.
My code for search:
self.company = self.companyDetails.filter{ _ in self.companyDetails.company_name.range(of: searchKey) }
Showing error:
Value of type '[companiesDetail]' has no member 'company_name'
Alamofire.request("http://34.210.142.70/isdental/api/v2.0/home/companies", method: .get, parameters: nil, encoding: URLEncoding.default, headers: params).responseObject { (response:DataResponse<ContactRealm>) in
let ContactsRes = response.result.value
self.companyDetails = ContactsRes?.companies as! [companiesDetail]
self.company = ContactsRes?.companies as! [companiesDetail]
}
Below is My JSON :
{
"error": false,
"message": "Companies fetched succesfully",
"companies": [
{
"company_id": 1,
"company_name": "3M Espe India",
"company_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/companies/3m_espe.png",
"company_website": "http://solutions.3mindia.co.in/wps/portal/3M/en_IN/3M-ESPE-APAC/",
"company_email": "",
"company_description": "",
"company_categories": "General Equipment / Preventives & Oral Care / General & Restorative",
"company_contacts": [
{
"contact_id": 1,
"contact_name": "Zonal Office",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/company_office.png",
"contact_phone": "+91 8022231414",
"contact_location": "Bangalore",
"contact_favourite": false,
"contact_email": "3mespe.in#mmm.com",
"contact_website": "",
"contact_type": 1
},
{
"contact_id": 367,
"contact_name": "3A Dental Company",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9811082743",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "3adental#sify.com",
"contact_website": "",
"contact_type": 4
},
{
"contact_id": 368,
"contact_name": "Avco Consultancy",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9811155330",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "avcoindia#gmail.com",
"contact_website": "",
"contact_type": 4
},
{
"contact_id": 369,
"contact_name": "Biotech Agencies",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9811132274",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "BIOTECHAGENCIES#GMAIL.COM",
"contact_website": "",
"contact_type": 4
},
{
"contact_id": 370,
"contact_name": "Lexical",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9810015540",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "lexicaldental#gmail.com",
"contact_website": "",
"contact_type": 4
},
{
"contact_id": 371,
"contact_name": "Oramco",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9810263014",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "oramco#yahoo.com",
"contact_website": "",
"contact_type": 4
},
{
"contact_id": 372,
"contact_name": "Unicorn Denmart",
"contact_image": "https://project-isdental-cammy92.c9users.io/api/images/v2.0/contacts/dealer.png",
"contact_phone": "+91 9810986086",
"contact_location": "Delhi",
"contact_favourite": false,
"contact_email": "achla#unicorndenmart.com",
"contact_website": "",
"contact_type": 4
}]}]}
Below is My Mapped Class :
import Foundation
import RealmSwift
import ObjectMapper
struct ContactRealm: Mappable {
init?(map: Map) {
}
var companies:Array<companiesDetail>?
mutating func mapping(map: Map) {
self.companies <- map["companies"]
self.filters <- map["filters"]
}
}
struct companiesDetail: Mappable {
init?(map: Map) {
}
var company_id : Int?
var company_name: String?
var company_image : String?
var company_website : String?
var company_email: String?
var company_description : String?
var company_categories : String?
var company_contacts:Array<companycontacts>?
mutating func mapping(map: Map) {
self.company_id <- map["company_id"]
self.company_name <- map["company_name"]
self.company_image <- map["company_image"]
self.company_website <- map["company_website"]
self.company_email <- map["company_email"]
self.company_description <- map["company_description"]
self.company_categories <- map["company_categories"]
self.company_contacts <- map["company_contacts"]
}
}
struct companycontacts: Mappable {
init?(map: Map) {
}
var contact_id : Int?
var contact_name : String?
var contact_image : String?
var contact_phone : String?
var contact_location : String?
var contact_favourite : String?
var contact_email : String?
var contact_website : String?
var contact_type : Int?
mutating func mapping(map: Map) {
self.contact_id <- map["contact_id"]
self.contact_name <- map["contact_name"]
self.contact_image <- map["contact_image"]
self.contact_phone <- map["contact_phone"]
self.contact_location <- map["contact_location"]
self.contact_favourite <- map["contact_favourite"]
self.contact_email <- map["contact_email"]
self.contact_website <- map["contact_website"]
self.contact_type <- map["contact_type"]
}
}

Resources