I have a request
Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON).responseJSON {
response in
var json = JSON(data: response.data!)
print(json)
print(json["res"])
}
followed by the result
{
"res" : "[{\"name\":\"testName\",\"lastName\":\"testLastName\"},{\"name\":\"testName\",\"lastName\":\"testLastName\"}]",
"status" : "success",
"out" : "{\"name\":\"testName\",\"lastName\":\"testLastName\"}"
}
[{"name":"testName","lastName":"testLastName"},{"name":"testName","lastName":"testLastName"}]
how i can set data from res to struct or class User
struct User {
var name : String?
var lastName : String?
}
please help to solve this problem) thank you very much !!)
You can do something like that
var result: [User]()
for user in json["res"] {
let userTmp = User(name: user["name"], lastName: user["lastName"])
result.append(userTmp)
}
Regards
Basically, it would be:
class User {
var name : String?
var lastName : String?
}
var theUsers = [User]()
Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON)
.responseJSON { response in
var json = JSON(data: response.data!)
print(json)
theUsers = json["res"].map {
return User (name: $0["name"], lastName: $0.["lastName"])
}
})
However, along the way, you might need some typecasting. For example, maybe replace json["res"] with (json["res"] as Array<Dictionary<String,String>>) in order to keep the type checker and type inferencer happy.
I'm using native Codable protocol to do that:
class MyClass: Codable {
var int: Int?
var string: String?
var bool: Bool?
var double: Double?
}
let myClass = MyClass()
myClass.int = 1
myClass.string = "Rodrigo"
myClass.bool = true
myClass.double = 2.2
if let json = JsonUtil<MyClass>.toJson(myClass) {
print(json) // {"bool":true,"string":"Rodrigo","double":2.2,"int":1}
if let myClass = JsonUtil<MyClass>.from(json: json) {
print(myClass.int ?? 0) // 1
print(myClass.string ?? "nil") // Rodrigo
print(myClass.bool ?? false) // true
print(myClass.double ?? 0) // 2.2
}
}
And I created a JsonUtil to help me:
public struct JsonUtil<T: Codable> {
public static func from(json: String) -> T? {
if let jsonData = json.data(using: .utf8) {
let jsonDecoder = JSONDecoder()
do {
return try jsonDecoder.decode(T.self, from: jsonData)
} catch {
print(error)
}
}
return nil
}
public static func toJson(_ obj: T) -> String? {
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(obj)
return String(data: jsonData, encoding: String.Encoding.utf8)
} catch {
print(error)
return nil
}
}
}
And if you have some issue with Any type in yours objects. Please look my other answer:
https://stackoverflow.com/a/51728972/3368791
Good luck :)
Related
I am trying to parse the data and display on the screen but i am getting " Value of type 'EmployeeData' has no member 'employee_name' "
What i am missing ?
I created my struct, parsed data and tried to divide into two parts. first part will be related with listing, second part is all data.
struct EmployeeData: Codable {
var data: Employee
var status: String
}
struct Employee: Codable {
var employee_name: String
var employee_salary: String
var employee_age: String
}
class WebServices {
func getData(completion: #escaping (EmployeeData?) -> ()){
guard let url = URL(string:"http://dummy.restapiexample.com/api/v1/employees")
else { fatalError("There is error!") }
URLSession.shared.dataTask(with: url) { (data, response,error) in
guard let data = data, error == nil else {
DispatchQueue.main.async{
completion(nil)
}
return
}
let empleyees = try? JSONDecoder().decode(EmployeeData.self, from: data)
DispatchQueue.main.async {
completion(empleyees)
}
}.resume()
}
}
class MVDesingnListView: ObservableObject {
}
struct MVDesignCellView {
let employeeDatas: EmployeeData
init(employeeDatas: EmployeeData) {
self.employeeDatas = employeeDatas
}
var employee_name: String {
self.employeeDatas.employee_name
}
}
The compiler is all right. Your struct EmployeeData has no member employee_name.
You need to go to the employee first, to get her name:
var employee_name: String {
self.employeeDatas.data.employee_name
}
should do the job.
Here, we have a scenario where I am facing issue for parsing the model class using "JSONDecoder".
Let me share you what I have done in this example and where I am facing issue:
There's a model protocol derived through the Codable.
A struct model and A class GenericExample
GenericExample class have following things:
shared instance
typeContainer which is the type of Protocol
There's two more methods staticClassParsing and dynamicClassParsing with one parameter dynamicType
In the last, One generic method which return the parsed data model.
Calling method for parsing the model:
GenericExample.shared.dynamicClassParsing(Numbers.self,data: "[\r\n{\"one\": \"1\"},\r\n{\"two\":\"2\"}\r\n]")
Compile Time Error:
Generic parameter 'T' could not be inferred
Occurred here
returnModelType: typeContainer.self
**For more details, please go through following code: **
protocol BaseMapModel : Codable { }
struct Numbers: BaseMapModel {
var one: String?
var two: String?
}
class GenericExample: NSObject {
static let shared = GenericExample()
var typeContainer : BaseMapModel.Type?
private override init() {
super.init()
}
}
extension GenericExample {
// Static Class Parsing passed through the conversion
func staticClassParsing() {
let dataJson = "[\r\n{\"one\": \"1\"},\r\n{\"two\":\"2\"}\r\n]"
convertTypeContainer(data: Data(dataJson.utf8), returnModelType: Numbers.self) { (mappedResult) in
print(mappedResult?.one ?? "")
print(mappedResult?.two ?? "")
}
}
// Dynamic Class Parsing can't passed through the conversion
// Error:- Generic parameter 'T' could not be inferred
// Error Parameter:- in "returnModelType: typeContainer.self"
func dynamicClassParsing(_ dynamicType: BaseMapModel.Type, data:String) {
typeContainer = dynamicType.self
convertTypeContainer(data: Data(data.utf8), returnModelType: typeContainer.self) { (mappedResult) in
print(mappedResult?.one ?? "")
print(mappedResult?.two ?? "")
}
}
}
extension GenericExample {
private func convertTypeContainer<T : BaseMapModel>(data:Data, returnModelType: T.Type, completion: ((_ result:T?)->Void)) {
guard let responseModel = try? JSONDecoder().decode(returnModelType.self, from: data) else {
completion(nil)
return
}
completion(responseModel)
}
}
typeContainer must be a concrete type, it cannot be a protocol. And the completion handler is pointless as JSONDecoder works synchronously.
To decode JSON with generics you have to use something like this, it's highly recommended to handle also the Decoding error
struct Numbers: Decodable {
var one: String?
var two: String?
}
class GenericExample: NSObject {
static let shared = GenericExample()
}
extension GenericExample {
func dynamicClassParsing<T : Decodable>(_ dynamicType: T.Type, data: String) -> Result<T,Error> {
return Result { try JSONDecoder().decode(T.self, from: Data(data.utf8)) }
}
}
let dataJson = """
[{"one": "1"},{"two":"2"}]
"""
let result = GenericExample.shared.dynamicClassParsing([Numbers].self, data: dataJson)
switch result {
case .success(let numbers): print(numbers)
case .failure(let error): print(error)
}
First of all, Thanks to All for your support. And Yes, I would like to post answer to my question.
class BaseMapModel : Codable { }
class Numbers: BaseMapModel {
var one: String?
var two: String?
enum CodingKeys: String, CodingKey {
case one = "one"
case two = "two"
}
// Decoding
required init(from decoder: Decoder) throws {
let response = try decoder.container(keyedBy: CodingKeys.self)
one = try? response.decode(String.self, forKey: .one)
two = try? response.decode(String.self, forKey: .two)
let superDecoder = try response.superDecoder()
try super.init(from: superDecoder)
}
}
class GenericExample: NSObject {
static let shared = GenericExample()
var defaultTypeContainer : Numbers.Type!
var typeContainer : BaseMapModel.Type?
private override init() {
super.init()
}
}
extension GenericExample {
// Static Class Parsing passed through the conversion
func staticClassParsing() {
let dataJson = "[\r\n{\"one\": \"1\"},\r\n{\"two\":\"2\"}\r\n]"
convertTypeContainer(data: Data(dataJson.utf8), returnModelType: Numbers.self) { (mappedResult) in
print(mappedResult?.one ?? "")
print(mappedResult?.two ?? "")
}
}
// Dynamic Class Parsing passed through the conversion
func dynamicClassParsing(_ dynamicType: BaseMapModel.Type, data:String) {
typeContainer = dynamicType.self
convertTypeContainer(data: Data(data.utf8), returnModelType: (typeContainer ?? defaultTypeContainer).self) { (mappedResult) in
print((mappedResult as? Numbers)?.one ?? "")
print((mappedResult as? Numbers)?.two ?? "")
}
}
}
extension GenericExample {
private func convertTypeContainer<T : BaseMapModel>(data:Data, returnModelType: T.Type, completion: ((_ result:T?)->Void)) {
guard let responseModel = try? JSONDecoder().decode(returnModelType.self, from: data) else {
completion(nil)
return
}
completion(responseModel)
}
}
I'm making an api call and getting the response like so..
if let data = NSData(contentsOf: NSURL(string: "http://test.chatongo.in/testdata.json")! as URL) {
do {
if let response = try JSONSerialization.jsonObject(with: data as Data, options: []) as? NSDictionary {
print("THE RESPONSE IS: \(response)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
And the response I get like so...
THE RESPONSE IS: {
Message = Success;
Status = 200;
data = {
Records = (
{
Id = 1;
collectedValue = 500;
endDate = "10/06/2018";
mainImageURL = "http://iphonedeveloperguide.com/oneinr/project1.jpg";
shortDescription = "This foundation will bring smile on there faces";
startDate = "05/05/2018";
title = "Smile Crowdfunding";
totalValue = 5000;
},
{
Id = 2;
collectedValue = 750;
endDate = "08/06/2018";
mainImageURL = "http://iphonedeveloperguide.com/oneinr/project10.jpg";
shortDescription = "This foundation will help animals";
startDate = "05/05/2018";
title = "Animal Funding";
totalValue = 20000;
}
);
TotalRecords = 10;
};
}
But how do I parse this json and get the individual elements out of it including the image, that I'm not able to figure out.
You need
import UIKit
class ViewController: UIViewController {
var records = [Record]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
URLSession.shared.dataTask(with: URL(string: "http://test.chatongo.in/testdata.json")!) { (data, response, error) in
guard let data = data else { return }
do {
let res = try JSONDecoder().decode(Root.self, from: data)
self.records = res.data.records
print(res.data.records)
// if it's a collection/table wrap the reload here inside DispatchQueue.main.async
}
catch {
print(error)
}
}.resume()
}
}
// MARK: - Empty
struct Root: Codable {
let status: Int
let message: String
let data: DataClass
enum CodingKeys: String, CodingKey {
case status = "Status"
case message = "Message"
case data
}
}
// MARK: - DataClass
struct DataClass: Codable {
let totalRecords: Int
let records: [Record]
enum CodingKeys: String, CodingKey {
case totalRecords = "TotalRecords"
case records = "Records"
}
}
// MARK: - Record
struct Record: Codable {
let id: Int
let title, shortDescription: String
let collectedValue, totalValue: Int
let startDate, endDate: String
let mainImageURL: String
enum CodingKeys: String, CodingKey {
case id = "Id"
case title, shortDescription, collectedValue, totalValue, startDate, endDate, mainImageURL
}
}
Tip : Don't use NS stuff in swift and avoid using Data(contentsOf: as it blocks the main thread
There are multiple ways, one way to create a modelobject of
struct RecordItem : Codable {
var id : Int?
var collectedValue : Int?
var endDate : String?
var mainImageURL: String?
var shortDescription : String?
var title :String?
var startDate : String?
var totalValue : Int?
}
and
struct Records : Codable {
var items : [RecordItem]?
}
and use this. = let item = data [index]
print (item. collectedValue) and so on.
seconds methods, you already created dict, then extract all keys and array objects using ["Key": "Value"] and set to any variable.
How to Convert a model object into JSON?
I want "Answer" object.
// Answers Class
class Answers {
var cat_id: String!
var responses = [Response]()
var date: String!
var comment: String!
var time: String!
var lat: String!
var lon: String!
var address: String!
}
// Response Class
class Response {
var que_id: String!
var question: String!
var response: String!
}
Make both types conform to Codable:
class Answers: Codable {
...
}
class Response: Codable {
...
}
And then use JSONEncoder:
let answers: Answers = ...
do {
let data = try JSONEncoder().encode(answers)
// use data here
} catch {
print(error)
}
See Encoding and Decoding Custom Types.
if you are using swift4, You can use encodable and decodable protocol. I'm still working on a heterogeneous list of objects. But this should work for you. Make your class conform to ABEncodable.
protocol ABDecodable: Decodable {
static func decodeFromData(_ data: Data) -> Decodable?
}
protocol ABEncodable: Encodable {
static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable
}
extension ABDecodable {
static func decodeFromData(_ data: Data) -> Decodable? {
do {
return try JSONDecoder().decode(self, from: data)
}
catch {
print(error)
}
return nil
}
}
extension ABEncodable {
static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable {
do {
return try JSONEncoder().encode(object)
}
catch {
return nil
}
}
}
//MARK: Decode mapper class
//Send jsonString or data to decode it into an required Object
final class Decode<T: Decodable> {
private func decodeData(_ data: Data) -> T? {
if let klass = T.self as? ABDecodable.Type {
if let object = klass.decodeFromData(data) as? T {
return object
}
}
else {
do {
return try JSONDecoder().decode(T.self, from: data)
}
catch {
print(error)
}
}
return nil
}
func fromJsonString(_ json: String) -> T? {
guard let data = json.data(using: String.Encoding.utf8) else { return nil }
if let object = decodeData(data) {
return object
}
return nil
}
func fromData(_ data: Data) -> T? {
if let object = decodeData(data) {
return object
}
return nil
}
}
//MARK: Encode mapper class
//Send jsonString or data to decode it into an required Object
final class Encode<N:Encodable> {
private func encodeObject(_ object: N) -> Data? {
if let klass = N.self as? ABEncodable.Type {
if let data = klass.encodeFromObject(object) {
return data
}
}
else {
do {
return try JSONEncoder().encode(object)
}
catch {
print(error)
}
}
return nil
}
func toJsonString(_ object: N) -> String? {
if let data = encodeObject(object) {
return String(data: data, encoding: .utf8)
}
return nil
}
func toData(_ object: N) -> Data? {
if let data = encodeObject(object) {
return data
}
return nil
}
}
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.