how to map the data which has array of data - ios

My response is :
[
{
"menu_code" : "NDS",
"items" : [
{
"unit" : "Nos",
"name" : "Chapathi\/Pulkas",
"quantity" : 2
},
{
"unit" : "Cup",
"name" : "Palya\/Curry",
"quantity" : 1
}
],
"is_active" : 1,
"image" : "nds.jpg",
"menu_name" : "Normal Diet South"
},
{
"menu_code" : "NCCD",
"items" : [
{
"menu_code" : "NDS",
"name" : "Monday"
},
{
"menu_code" : "NDN",
"name" : "Tuesday"
}
],
"is_active" : 1,
"image" : "NCCD.jpg",
"menu_name" : "Normal Combo Corporate Diet"
}
]
Today 2 format i have .In this both format only my data will come from response.And i need to show them in collection view.
My api call :
func getAllCatogory(){
TransportManager.sharedInstance.AllCatogory { (dt, err) in
if let _ = err{
}else{
if let data = dt as? String {
let pro = Mapper<AllCatagories>().map(JSONString: data)
print(data) // getting data
print(pro as Any) // getting nil
}
}
}
}
My model :
class AllCatagories: Mappable{
var menu_code = ""
var items: Array<AllCatProducts> = []
var is_active = 0
var image = ""
var menu_name = ""
required init?(map: Map) {
}
init() {
}
func mapping(map: Map) {
menu_name <- map["menu_name"]
is_active <- map["is_active"]
menu_code <- map["menu_code"]
image <- map["image"]
items <- map["items"]
}
}
Below i have created one more model class for the item inside my json.
class AllCatProducts: Mappable{
var name = ""
var quantity = 0
var unit = ""
var menu_code = ""
required init?(map: Map) {
}
init() {
}
func mapping(map: Map) {
name <- map["name"]
quantity <- map["quantity"]
unit <- map["unit"]
menu_code <- map["menu_code"]
}
}
The issues is i am getting nil in my pro.Not sure when i am doing wrong.
Thanks

You can try
struct AllCatagories: Codable {
let menuCode: String
let items: [AllCatProducts]
let isActive: Int
let image, menuName: String
}
struct AllCatProducts: Codable {
let unit: String?
let name: String
let quantity: Int?
let menuCode: String?
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let str = dt as? String else { return }
let res = try decoder.decode([AllCatagories].self, from:str.data(using: .utf8)!)
print(res)
}
catch {
print(error)
}

Related

Swift Retrieve Data with Nested Array

I am trying to pass data into variable by displaying it(NameList and BasketDetail). But the basket data is empty(BasketDetail). How can i solve this (Output:Retrieve data: [“name”: Mike, “basket”: <__NSArray0 0x28112c060()])?
Firebase node;
"Pro_" : {
"-MsVcfY7pZI74r0E1ULD" : {
"basket" : {
"-Mruf-UdXxpLK0l8Qgw4" : {
"cat" : "Tech",
"info" : "iOS",
"orderid" : "Ref_1",
},
"-MszuLj3cxm_gE9m-VPO" : {
"cat" : "Tech",
"info" : "Android",
"orderid" : "Ref_2",
}
},
"name" : "-Mike",
}
}
My function;
private func populateNameLists() {
ref = Database.database().reference()
self.ref.child(“Pro_”).observeSingleEvent(of:.value) { (snapshot) in
self.nameLists.removeAll()
let nameListDictionary = snapshot.value as? [String:Any] ?? [:]
for (key,_) in nameListDictionary {
if let nameListDictionary = nameListDictionary[key] as? [String:Any] {
if let nameList = NameList(nameListDictionary) {
self.nameLists.append(nameList)
print(“Retrieve data:”, try! nameList.toDictionary())
}}}}}
Output(Basket's empty ???)
Retrieve data: [“name”: Mike, “basket”: <__NSArray0 0x28112c060()]
Name List
typealias JSONDictionary = [String:Any]
class NameList : Codable {
var basket :[BasketDetail] = [BasketDetail]()
var name: String!
init(name:String ) {
self.name = name
}
init?(_ dictionary :[String:Any]) {
guard let name = dictionary[“name”] as? String else {
return nil
self.name = name
let basketItemsDictionary = dictionary[“basket”] as? [JSONDictionary]
if let dictionaries = basketItemsDictionary {
self.basket = dictionaries.compactMap(BasketDetail.init)
}}}
Basket Detail
class BasketDetail : Codable{
var cat : String
var info : String
var orderid : String
init(cat :String, info :String, orderid :String) {
self.cat = cat
self.info = info
self.orderid = orderid
}
init?(dictionary :JSONDictionary) {
guard let cat = dictionary["cat"] as? String else {
return nil
}
guard let info = dictionary["info"] as? String else {
return nil
}
guard let orderid = dictionary["orderid"] as? String else {
return nil
}
self.cat = cat
self.info = info
self.orderid = orderid
}}

Getting data but not able to display correctly

I am fetching some data and displaying in my screen.
func getAllCatogory(){
ViewUtils.addActivityView(view: self.view)
TransportManager.sharedInstance.AllCatogory { (dt, err) in
ViewUtils.removeActivityView(view: self.view)
if let _ = err{
}else{
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let str = dt as? String else { return }
let res = try decoder.decode([AllCatagories].self, from:str.data(using: .utf8)!)
self.allCategory = res
self.collectionView.reloadData()
print(res.count) // getting count 2
print(self.allCategory.count as Any) getting count 2
}
catch {
print(error)
}
}
}
}
But in my collection view when i am going to append or print its not coming.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionCell", for: indexPath) as! HomeCollectionCell
let ct = self.allCategory[indexPath.item]
print(ct.menuName as Any) // getting null
//cell.productName.text = ct.menuName
return cell
}
Not sure what might be an issue.Any help on this ??
Thanks in advance !
Update :
class AllCatagories: Codable{
let image : String?
let isActive : Int?
let items : [Item]?
let menuCode : String?
let menuName : String?
enum CodingKeys: String, CodingKey {
case image
case isActive = "is_active"
case items
case menuCode = "menu_code"
case menuName = "menu_name"
}
}
struct Item : Codable {
let menuCode : String?
let name : String?
enum CodingKeys: String, CodingKey {
case menuCode = "menu_code"
case name
}
}
here is my model class which i am using for.Main thread to reload the collection view means where exactly ?
Update :
[
{
"menu_code" : "NDS",
"items" : [
{
"unit" : "Nos",
"name" : "Chapathi\/Pulkas",
"quantity" : 2
},
{
"unit" : "Cup",
"name" : "Palya\/Curry",
"quantity" : 1
}
],
"is_active" : 1,
"image" : "nds.jpg",
"menu_name" : "Normal Diet South"
},
{
"menu_code" : "NCCD",
"items" : [
{
"menu_code" : "NDS",
"name" : "Monday"
},
{
"menu_code" : "NDN",
"name" : "Tuesday"
}
],
"is_active" : 1,
"image" : "NCCD.jpg",
"menu_name" : "Normal Combo Corporate Diet"
}
]
my json response is here
If you specify convertFromSnakeCase you have to delete the coding keys, that's the purpose of convertFromSnakeCase
And declare the members / properties as much as possible non-optional, not the contrary. In this particular case you would get a Decoding error.
struct AllCatagories: Codable {
let image : String
let isActive : Int
let items : [Item]
let menuCode : String
let menuName : String
}
struct Item : Codable {
let unit : String?
let name : String
let quantity : Int?
let menuCode : String?
}
And reload the collection view on the main thread
DispatchQueue.main.async {
self.collectionView.reloadData()
}

JSON to Multidimensional Array

I'm trying to take my JSON from a HTTP POST and put it in a multidimensional array to use for sections / table cells in Swift.
I would like each table section to use these dynamic keys (submitid) and insert the cell data for each:
15302992338145
15301374235890
15302930963080
My JSON:
let swiftyJsonVar = JSON(data!)
{
"data" : {
"15302992338145" : [
{
"date" : "2018-06-27",
"username" : "user1",
"submitid" : 15302992338145,
"notes" : "Testing"
},
{
"date" : "2018-06-28",
"username" : "user1",
"submitid" : 15302992338145,
"notes" : "Testing"
}
],
"15301374235890" : [
{
"date" : "2018-06-21",
"username" : "user2",
"submitid" : 15301374235890,
"notes" : "Comments one two three"
},
{
"date" : "2018-06-22",
"username" : "user2",
"submitid" : 15301374235890,
"notes" : "N/A"
}
],
"15302930963080" : [
{
"date" : "2018-07-03",
"username" : "user3",
"submitid" : 15302930963080,
"notes" : "Hello"
}
]
}
}
I've tried but with no luck:
if let resData = swiftyJsonVar["data"][].arrayObject {
self.arrRes = resData as! [String: [[String:AnyObject]]]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return arrRes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath)
// Configure the cell...
var dict = arrRes[indexPath.section][indexPath.row]
cell.dateLabel?.text = dict["date"]
return cell
}
You should stop using SwiftyJSON and move up to Swift 4 and Decodable:
struct User : Decodable {
let date : String
let username : String
let submitid : Int
let notes : String
}
struct Result : Decodable {
let data : [[User]]
struct AnyCodingKey : CodingKey {
var stringValue: String
var intValue: Int?
init(_ codingKey: CodingKey) {
self.stringValue = codingKey.stringValue
self.intValue = codingKey.intValue
}
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
init(from decoder: Decoder) throws {
let con = try! decoder.container(keyedBy: AnyCodingKey.self)
let intermediate = try! con.decode([String:[User]].self,
forKey: AnyCodingKey(stringValue:"data"))
var data = [[User]]()
for d in intermediate {
data.append(d.value)
}
self.data = data
}
}
// jsondata is your original JSON data, as you downloaded it
let result = try! JSONDecoder().decode(Result.self, from: jsondata)
After that, result.data is an array of array of User.
[[User(date: "2018-07-03", username: "user3",
submitid: 15302930963080, notes: "Hello")],
[User(date: "2018-06-27", username: "user1",
submitid: 15302992338145, notes: "Testing"),
User(date: "2018-06-28", username: "user1",
submitid: 15302992338145, notes: "Testing")],
[User(date: "2018-06-21", username: "user2",
submitid: 15301374235890, notes: "Comments one two three"),
User(date: "2018-06-22", username: "user2",
submitid: 15301374235890, notes: "N/A")]]

How to create a function to show reviews in a view of my application (Swift-JSON)

I'm following https://developers.google.com/places/web-service/details this doc to add all the information about a place, and for example to add "geometry"
"geometry" : {
"location" : {
"lat" : -33.866651,
"lng" : 151.195827
},
i created this function in my class that work well
private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
class EClass: NSObject {
var location: CLLocationCoordinate2D?
init(placeInfo:[String: Any]) {
placeId = placeInfo["place_id"] as! String
// coordinates
if let g = placeInfo[geometryKey] as? [String:Any] {
if let l = g[locationKey] as? [String:Double] {
if let lat = l[latitudeKey], let lng = l[longitudeKey] {
location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
}
}
}
}
but but i'm having difficulty adding "reviews"
"reviews" : [
{
"author_name" : "Robert Ardill",
"author_url" : "https://www.google.com/maps/contrib/106422854611155436041/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/-T47KxWuAoJU/AAAAAAAAAAI/AAAAAAAAAZo/BDmyI12BZAs/s128-c0x00000000-cc-rp-mo-ba1/photo.jpg",
"rating" : 5,
"relative_time_description" : "a month ago",
"text" : "Awesome offices. Great facilities, location and views. Staff are great hosts",
"time" : 1491144016
}
],
i tried to follow the same concept of the function i created for geometry like this
if let t = place.details?["reviews"] as? [String:Any] {
if let n = t["author_name"], let m = t["text"] {
Mylabel.text = "\(t)"
}
but is not working, i also tried to add a breakpoint and only the first line enters. What can i do? How can i create a build to show the review with a label or anything i need?
Take advantage of Codable in Swift 4. You can simply convert your JSON into a specific struct. e.g. Based on your JSON:
let json = """
{
"reviews" : [
{
"author_name" : "Robert Ardill",
"author_url" : "https://www.google.com/maps/contrib/106422854611155436041/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/-T47KxWuAoJU/AAAAAAAAAAI/AAAAAAAAAZo/BDmyI12BZAs/s128-c0x00000000-cc-rp-mo-ba1/photo.jpg",
"rating" : 5,
"relative_time_description" : "a month ago",
"text" : "Awesome offices. Great facilities, location and views. Staff are great hosts",
"time" : 1491144016
}
]
}
"""
You can convert it into a Response struct using the following code:
struct Response: Codable {
struct Review: Codable, CustomStringConvertible {
let text: String
let authorName: String
var description: String {
return "Review text: \(text) authorName: \(authorName)"
}
enum CodingKeys: String, CodingKey {
case text
case authorName = "author_name"
}
}
let reviews: [Review]
}
do {
if let data = json.data(using: .utf8) {
let decoder = JSONDecoder()
let decoded = try decoder.decode(Response.self, from: data)
print(decoded.reviews)
} else {
print("data is not available")
}
} catch (let e) {
print(e)
}
In your code t is not a Dictionary it is an Array instead. So try doing something like this. Rest of that you can change as per your logic.
if let t = place.details?["reviews"] as? [String:Any] {
for dic in t {
if let n = dic["author_name"], let m = dic["text"] {
Mylabel.text = "\(t)"
}
}
}
Yeah, but You can also try to make it like that:
struct reviews: Codable{
var reviews: [review]?
}
struct review: Codable{
var author_name: String?
var author_url: String?
var language: String?
var profile_photo_url: String?
var rating: Int?
var relative_time_description: String?
var text: String?
var time: Int?
}
And then:
if let dict = place.details?["reviews"] as? [String: Any],
let dataToDecode = dict.data(using: .utf8){
do{
let decodedReviews = try JSONDecoder().decode(reviews.self, from: dataToDecode)
// here you have decoded reviews in array
}catch let err{
print(err)
}
}

How to make model class for following JSON response in swift iOS

Hi i am beginner for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below
MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please
JsonResponse:-
[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
"city" : "Madrid"
}
}, {
"_id" : "540b2ff281b30f3504a1c72f",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
"name" : "Teatro Kapital",
"hasVippler" : false,
"location" : {
"address" : "Atocha, 125",
"city" : "Madrid"
}
}, {
"_id" : "540cd44581b30f3504a1c73b",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
"name" : "Charada",
"hasVippler" : false,
"location" : {
"address" : "La Bola, 13",
"city" : "Madrid"
}
}]
mapping:
Club:-
class Club {
var id: String = ""
var name: String = ""
var imageUrl: String = ""
var hasVip: Bool = false
var desc: String = ""
var location: [Location] = []
}
Location:-
class Location {
var country: String = ""
var city: String = ""
var address: String = ""
var zip: String = ""
var underground: [String] = []
}
NSURlSession code:-
class BackGroundPostCall: NSObject {
var delegate:PostProtocol?
func callPostService(url:String,params:NSDictionary){
print("url is===>\(url)")
let request = NSMutableURLRequest(URL: NSURL(string:url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
print("Response: \(json)")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
}
For mapping you can use Alamofire's extension ObjectMapper.
Ex:
[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
"city" : "Madrid"
}
}, {
"_id" : "540b2ff281b30f3504a1c72f",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
"name" : "Teatro Kapital",
"hasVippler" : false,
"location" : {
"address" : "Atocha, 125",
"city" : "Madrid"
}
}, {
"_id" : "540cd44581b30f3504a1c73b",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
"name" : "Charada",
"hasVippler" : false,
"location" : {
"address" : "La Bola, 13",
"city" : "Madrid"
}
}]
And mapper class:
import ObjectMapper
class Location: Mappable {
var address: String?
var city: String?
required init?(map: Map){
}
func mapping(map: Map) {
address <- map["address"]
city <- map["city"]
}
}
class Club: Mappable {
var id: String?
var imageUrl: Int?
var name: String?
var hasVip: Bool = false
var location: Location?
required init?(map: Map){
}
func mapping(map: Map) {
id <- map["_id"]
imageUrl <- map["imageUrl"]
name <- map["name"]
hasVip <- map["hasVippler"]
location <- map["location"]
}
}
And this way very flexible and transparent to use.
https://github.com/Alamofire/Alamofire
https://github.com/tristanhimmelman/AlamofireObjectMapper
Using example:
Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in
let clubs = response.result.value
if let clubs = clubs {
for club in clubs {
print(club.name)
print(club.location.city)
}
}
}
You can make model class using this url : http://www.jsoncafe.com/
open this link and put your json in JSON tab and select any Code Template that is you want. and there is you can also add prefix class name and root class name if you want other wise it is optional. and last click on generate button, your json class is ready.!!
Step1: Create your model like below.
class Club {
var id: String = ""
var name: String = ""
var imageUrl: String = ""
var hasVip: Bool = false
var desc: String = ""
var location = Location()
init?(dictionary:[String:Any],location: Location) {
guard let id = dictionary["_id"],
let name = dictionary["name"],
let imageUrl = dictionary["imageUrl"],
let hasVip = dictionary["hasVippler"]
else {
return nil
}
self.id = id
self.name = name
self.imageUrl = imageUrl
self.hasVip = hasVip
self.location = location
}
}
}
class Location {
var country: String = ""
var city: String = ""
var address: String = ""
var zip: String = ""
init?(dictionary:[String:Any]) {
guard let country = dictionary["country"],
let city = dictionary["city"],
let address = dictionary["address"],
let zip = dictionary["zip"]
else {
return nil
}
self.country = country
self.city = city
self.address = address
self.zip = zip
}
}
}
Step2: Declare your array as below.
var myTargetArray = [Club]()
Step3: Json Parsing.
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
print("Response: \(json)")
for club in json {
if let clubDictionary = club as? NSDictionary {
if let locationDict = clubDictionary["location"] as? NSDictionary{
if let location = Location(dictionary: locationDict) {
if let clubObj = Club(dictionary: clubDictionary, location:location) {
myTargetArray.append(clubObj)
}
}
}
}
}
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
Note: I removed underground array from location model since your json data does not contain it.
Finally you can use your target array as your tableview source. Happy coding...
Model class:
class test : Unboxable {
let id : String
let imageURl : String
let name : String
let hasVip : Bool
let city : String
required init(unboxer: Unboxer) throws {
self.id = unboxer.unbox(key: "id") ?? ""
self.imageURl = unboxer.unbox(key: "imageUrl") ?? ""
self.name = unboxer.unbox(key: "name") ?? ""
self.hasVip = unboxer.unbox(key: "hasVip") ?? false
self.city = (unboxer.unbox(key: "city") ?? nil)!
}
}
parse json:
if let object = json as? [Any] {
// json is an array
var data :[test] = []
for respObject in object {
var dict = respObject as? Dictionary<String,AnyObject>
dict?["city"] = dict?["location"]?["city"] as AnyObject
let result1: [test] = try unbox(dictionaries: [dict!])
data.append(contentsOf: result1)
}
print(data)
For more details follow
https://github.com/JohnSundell/Unbox
**Api call with model class, swiftyjson and alamofire,Pod install alamofire and swiftyjson libraries, create collection view cell class, Create a class and write the following code
**
import UIKit
import Alamofire
import SwiftyJSON
var myResponse : JSON? = nil
var users : [reasonList] = []
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
feedbackApi()
}
func feedbackApi(){
DispatchQueue.main.async {
let url = URL(string: "--------")
let urlRequest = URLRequest(url: url!)
Alamofire.request(urlRequest)
.responseJSON { response in
switch response.result{
case.success(let data):
print("dddd :",data)
self.myResponse = JSON(data)
print(self.myResponse as Any)
let a = self.myResponse![0]["reasonList"]
print(a)
for i in 0..<a.count{
let single = reasonList(reasonListJson: a[i])
self.users.append(single)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print("dddd",error)
}
}
}
}
}
create a model class
import Foundation
import SwiftyJSON
class user{
var deviceId = String()
var deviceName = String()
var deviceLocationId = Int()
var locationName = String()
var welcomeText = String()
var reason=[reasonList]()
init(userJson:JSON) {
self.deviceId = userJson["deviceId"].stringValue
self.deviceName = userJson["deviceName"].stringValue
self.deviceLocationId = userJson["deviceLocationId"].intValue
self.locationName = userJson["locationName"].stringValue
self.welcomeText = userJson["welcomeText"].stringValue
self.reason = [reasonList(reasonListJson: userJson["reason"])]
}}
class reasonList{
var reason = String()
var id = Int()
init(reasonListJson:JSON) {
self.reason = reasonListJson["reason"].stringValue
self.id = reasonListJson["id"].intValue
]}
**create a collection view in view **
import UIKit
import Alamofire
import SwiftyJSON
class ReasonViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
//DelayCall()
// Do any additional setup after loading the view.
}
func DelayCall() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
_ = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController")as! HomeViewController
self.navigationController?.popViewController(animated: true)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReasonCollectionViewCell", for: indexPath) as! ReasonCollectionViewCell
let useee = users[indexPath.row]
print(useee)
cell.reasonLabel.text = useee.reason
return cell
}}
You can make model class using this url : https://www.json4swift.com/
Open this link and paste your JSON and select from below option you want. Click generate, it will generate class files you can download and used it in your project.

Resources