How to fecth data from array with model class - json

I am not getting data from the array using model class, but array have data in it. I don't know the correct way of using model classes. Maybe the way i implemented is wrong. Please guide.
Code:
// . ViewController class
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell: VisitorsCell = tableView.dequeueReusableCell(withIdentifier: "VisitorsCell", for: indexPath) as! VisitorsCell
let cell:RecentVisitorsCell = self.tblView.dequeueReusableCell(withIdentifier: "VisitorsCell") as! VisitorsCell
**let ds:VisitorDs = recentVisitorsArray[indexPath.row] as! VisitorsDs // . crash here.//**
// let ds = VisitorsDs()
cell.imgProfile.image = UIImage(named: ds.profile)
cell.lblAge.text = ds.age as String
return cell
}
//MARK: Delegatres Server Communication
func didFinishServerCommunicationWithSuccess(_ response:ServerResponse){
print("api response: ", response.infoResponse?["data"] as! [AnyObject])
//VisitorsArray = response.infoResponse?["data"] as! [AnyObject] as NSArray
//if response.operation == "SERVICE_SOURCE" {
if let dictResult = response.infoResponse as? NSDictionary {
if let arrResult = dictResult.object(forKey: "data") as? NSArray
{
for result in arrResult {
let Visitors = VisitorsDs()
recentVisitors.initWithVal(dict: result as! NSDictionary)
VisitorsArray.add(VisitorsDs.self)
}
print("array received: ", VisitorsArray)
self.tblView.reloadData()
}
}
self.tblView.reloadData()
}
// Model class
class VisitorsDs:NSObject {
var profile:String = ""
var name:String = ""
/*
//MARK: Initialization
init(profile:String,name:String,age:String,parentsName:String,mobile:String,purpose:String,date:String,time:String,clinic:String ) {
self.profile = profile
self.name = name
}
*/
func initWithVal(dict: NSDictionary) {
// print(dict)
if let latestValue = dict["image_path"] as? String {
self.profile = latestValue
}
if let latestValue = dict["first_name"] as? String {
self.name = latestValue
}
}
}
Error: Could not cast value of type 'IPAN.VisitorsDs' (0x10d809f58) to 'IPAN.VisitorsDs' (0x10d806eb0).
Please guide, values are empty in uitableview, but value exist in array.

I would recommend to use new Swift 4 Codable protocol to parse JSON into models and then you can use much easier in your tableview. One tutorial:
https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375
BTW what is in your response?

Related

How to work with Core Data saving JSON response,Show data when internet is offline in Swift 3?

I have already parsed JSON and showing in tableView which is working fine. Now my question is how will i save data offline and show when internet is not available offline using Core Data. I am working in Swift 3. If anyone can help me with screenshot it will be great help.
Below is my Code for fetching json and showing on tableView :
import UIKit
import SystemConfiguration
struct CellData {
var name:String
var address:String
public init(name:String,address:String){
self.name = name
self.address = address
}
}
///ViewController
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableViewData: UITableView!
var arrayData = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
if Reachability.isConnectedToNetwork(){
print("Internet Connection Available!")
fetchServerData()
}else{
let alert = UIAlertController(title: "No Internet connection", message: "Please ensure you are connected to the Internet", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print("Internet Connection not Available!")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellData
cell.lblTop.text = "😀\(arrayData[indexPath.row].name)"
cell.lblBottom.text = arrayData[indexPath.row].address
return cell
}
func fetchServerData(){
let prs = [
"author_id": "1780",
"get_deals_author": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let json = result as? NSDictionary
if let data = json as? [String:Any]{
if let err = data["status"] as? String, err == "success"{
if let data = data["result"] as? [Any]{
var arrayData = [CellData]()
for sectionObj in data{
if let sectionObjVal = sectionObj as? [String:Any]{
if let name_deal = sectionObjVal["name"] as? String{
if let address_deal = sectionObjVal["address"] as? String{
let dataValue = CellData.init(name: name_deal, address: address_deal)
arrayData.append(dataValue)
}
}
}
}
DispatchQueue.main.async { () -> Void in
self.arrayData.removeAll()
self.arrayData = arrayData
self.tableViewData.reloadData()
}
}
}
}
})
}
}
For Core Data, you need to create the entities you need in CoreData model .xcdatamodeld. Click on Add Entity and name your entity. Then add attributes which you require to save.
You can see this link on how to create the entities and attributes. After creating everything, we can write a CoreDataStack and a manager class or we can directly use the code pre-written in AppDelegate when we check on Core Data when creating a project. I'll here use the CoreDataStack class.
Here is the class
import Foundation
import CoreData
class CoreDataStack: NSObject {
static let moduleName = "YourProject"
static let shared = CoreDataStack()
private override init() {
super.init()
_ = self.persistentContainer
}
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: CoreDataStack.moduleName)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
print("Coordinator URL - \(storeDescription)")
})
return container
}()
}
Now we can make a manager class to insert the data. Let's say your entity is Person and its attributes are name and address
Here is the CoreDataManager class to insert, update, fetch data.
import UIKit
import CoreData
class CoreDataManager: NSObject {
class func addRecord(object:[String:Any]) {
let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: CoreDataStack.shared.persistentContainer.viewContext) as! Person
person.name = object["name"] as? String
person.address = object["address"] as? String
CoreDataStack.shared.saveContext()
}
class func getRecords() -> [Person]? {
let request:NSFetchRequest<Person> = Person.fetchRequest()
do {
let results = try CoreDataStack.shared.persistentContainer.viewContext.fetch(request)
return results
} catch {
print(error.localizedDescription)
}
return nil
}
}
You can call addRecord method in your ViewController class and it will save your data. I recommend that you pass the complete array and then add in core data and finally call saveContext().
Finally you can use getRecords to get all records.

How to show Json data in Offline using core data

Here i have created table view with labelName and labelUsername,
and i have downloaded Json data and saving it in core data entity called Details which contains attributes name and username..
here table view showing its data in online...
but how can i show fetched data in table view while in offline..
please help me in the code...
import UIKit
import CoreData
struct JsonData {
var nameS: String
var usernameS: String
init(name: String, username: String) {
self.nameS = name
self.usernameS = username
}
}
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var iteamsArray = [JsonData]()
override func viewDidLoad() {
downloadJson()
}
func downloadJson(){
let urlStr = "https://jsonplaceholder.typicode.com/users"
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: data!, options: .allowFragments) as! [[String: Any]]
for items in jsonObj {
let nameJson = items["name"] as? String
let usernameJson = items["username"] as? String
let coreData = NSEntityDescription.insertNewObject(forEntityName: "Details", into: self.context) as! Details
coreData.name = nameJson
coreData.username = usernameJson
self.iteamsArray.append(JsonData(name: nameJson!, username: usernameJson!))
}
try self.context.save()
//fetching from core data
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
let details = try self.context.fetch(fetchRequest)
if details.count > 0 {
for detail in details as [NSManagedObject] {
let nameCore = detail.value(forKey: "name")
let usernameCore = detail.value(forKey: "username")
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
// MARK: - TableView
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return iteamsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JsonCell", for: indexPath) as! JsonTableViewCell
let aData = iteamsArray[indexPath.row]
cell.labelName.text = aData.nameS
cell.labelUsername.text = aData.usernameS
cell.selectionStyle = .none
return cell
}
}
First of all forget the custom struct. Use the NSManagedObject class as data source array.
var iteamsArray = [Details]()
In viewDidLoad first fetch the data, if the array is empty load it from the web service
override func viewDidLoad() {
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
do {
iteamsArray = try self.context.fetch(fetchRequest)
if iteamsArray.isEmpty {
downloadJson()
} else {
self.tableView.reloadData()
}
} catch { print(error) }
}
In downloadJson() replace
self.iteamsArray.append(JsonData(name: nameJson!, username: usernameJson!))
with
self.iteamsArray.append(coreData)
and remove these lines
//fetching from core data
let fetchRequest : NSFetchRequest<Details> = Details.fetchRequest()
let details = try self.context.fetch(fetchRequest)
if details.count > 0 {
for detail in details as [NSManagedObject] {
let nameCore = detail.value(forKey: "name")
let usernameCore = detail.value(forKey: "username")
}
}
In cellForRow get the values directly from the NSManagedObject objects
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JsonCell", for: indexPath) as! JsonTableViewCell
let aData = iteamsArray[indexPath.row]
cell.labelName.text = aData.name
cell.labelUsername.text = aData.userName
cell.selectionStyle = .none
return cell
}

How to get JSON data and show it on a table view cell

I passed a JSON data to this table view controller. How to get the JSON data and show it on a table view cell?
When I print passedData I receive the following output:
["jobs": <__NSArrayM 0x17005d9d0>
({
jobDate = "2017-08-31";
jobEndTime = 1504144800;
jobID = 87;
jobTime = 1504137600;
},
{
jobDate = "2017-08-31";
jobEndTime = 1504173600;
jobID = 89;
jobTime = 1504170000;
}),
"result": success,
"message": Retrieve Sucessfully]
This is the code I'm using:
var passedData: [String: Any]!
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let jobs = passedData["jobs"] as? [[String:Any]] else {return 0}
return jobs.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
// jobs[indexPath.row] display jobTime
return cell
}
Instead of giving you a reply on the subject I would try to help understanding the domain you are working with.
The JSON response you are retrieving contains an array (jobs) where each element is an object. In fact, the JSON syntax states that:
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
If you are using JSONSerialization class, then you will have a dictionary that will contain an array of dictionaries.
A simple snippet like this will give you that array
if let jsonArray = jsonDict["jobs"] as? [[String: Any]] {
print(jsonArray)
}
Now, in order to access elements of that array you can do like the following:
let jsonArrayDict = jsonArray[0]
print(jsonArrayDict["jobTime"] ?? 0)
Obviously the code here is not production ready since you need to pay attention to possible crashes of your app.
What I really suggest is to work with a model that can be passed to your table view cell. This approach has these benefits:
avoid using optionals
document your code
unit test your code
etc.
Here an example on how to convert your JSON object into a specific model. Run it in a playground and practice.
struct Job {
let jobDate: String
let jobEndTime: Int
let jobID: Int
let jobTime: Int
}
extension Job {
init?(dict: [String: Any]) {
guard let jobDate = dict["jobDate"] as? String,
let jobEndTime = dict["jobEndTime"] as? Int,
let jobID = dict["jobID"] as? Int,
let jobTime = dict["jobTime"] as? Int else {
return nil
}
self.jobDate = jobDate
self.jobEndTime = jobEndTime
self.jobID = jobID
self.jobTime = jobTime
}
}
extension Job: CustomStringConvertible {
var description: String {
return "Job: \(jobDate) \(jobEndTime) \(jobID) \(jobTime)"
}
}
let jsonString = """
{
"jobs": [
{
"jobDate": "2017-08-31",
"jobEndTime": 1504144800,
"jobID": 87,
"jobTime": 1504137600
},
{
"jobDate2": "2017-08-31",
"jobEndTime": 1504144800,
"jobID": 87,
"jobTime": 1504137600
}
],
"result": "success",
"message": "Retrieve Sucessfully"
}
"""
if let jsonData = jsonString.data(using: .utf8), let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []),
let jsonDict = jsonObject as? [String: Any],
let jsonArray = jsonDict["jobs"] as? [[String: Any]] {
let jobs = jsonArray.flatMap { Job(dict: $0) }
print(jobs)
} else {
print("No Results")
}
This should help you understand the steps needed to parse and use the JSON data that you have. You will likely need to create a custom UITableViewCell which is beyond the scope of this answer. There are plenty of resources online which will explain this part of the process.
You will also need to convert your timestamps to dates, there are alot of answers on StackOverflow that can help with this. Like this one
Mapping JSON Data
let passedJsonStr = "{\"jobs\":[{\"jobDate\":\"2017-08-31\",\"jobEndTime\":1504144800,\"jobID\":87,\"jobTime\":1504137600},{\"jobDate\":\"2017-08-31\",\"jobEndTime\":1504173600,\"jobID\":89,\"jobTime\":1504170000}],\"result\":\"success\",\"message\":\"Retrieve Sucessfully\"}"
struct Job {
var jobDate: String
var jobEndTime: Int
var jobID: Int
var jobTime: Int
init(dict: [String:AnyObject]) {
// unwrap these safely, I'm just giving an example
self.jobDate = dict["jobDate"] as! String
self.jobEndTime = dict["jobEndTime"] as! Int
self.jobID = dict["jobID"] as! Int
self.jobTime = dict["jobTime"] as! Int
}
}
var jobs = [Job]()
if let data = passedJsonStr.data(using: String.Encoding.utf8) {
if let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] {
if let jsonData = jsonObject["jobs"] as? [[String:AnyObject]] {
jobs = jsonData.map { Job(dict: $0) }
}
print(jobs)
}
}
Displaying in UITableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
let job = self.jobs[indexPath.row]
cell.titleLabel.text = job.jobDate
return cell
}

Problems with adding value to an array with array.append() in Swift

in the moment we're programming a Swift App for iOS in which we want to get data of our JSON Website (MySql database) into the TableViewCell. The problem is by appending the text values of the strings for the label in the cell. Swift can import the JSON values into the name variable but I cant assign it to the text array for the cells. I havent no syntax errors, but the data[0] Variable print sth. as "123". Why it is 123? The test Value is "Test". I don't now where the problem by appending the value to the array is, that the result is 123 after that. Please help.
Here is the sourcecode:
class listViewViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var data:[String?] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let myUrl = URL(string: "");//Empty link for this question
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "lid=1";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let Name = parseJSON["Name"] as? String
print("\(Name)")//Test
self.data.append(Name!)
print("\(data![0])" as String)//123
}
} catch {
print(error)
}
}
task.resume()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! listViewTableViewCell
print("\(data[indexPath.row])")
let dataCell = data[indexPath.row]
cell.listViewCell.text = dataCell
return cell
}
}
this because your array properties and data callback block parameter have the same name "data". in your code you user print("(data![0])" as String) instead of print("(self.data![0])" as String) => you have to add self.
then you can optimise your code like this (it's optional : it's just like a code review ;) )
try to do this
- change your array type to String like this
var data = [String]()
- webService callback change your code like this :
if let parseJSON = json {
if let Name = parseJSON["Name"] as? String{
print("\(Name)")
self.data.append(Name)
print("\(self.data.last)")//123
}
}
When you append to your data array you use self.data but you then print from data which is the parameter to the inner function. You add and print from different arrays.

How to parse this json with Alamofire 4 in Swift 3?

I have the json below but unable to figure out how to parse it in Swift 3. My code is below. The json from the API has an array root. I am using Xcode 8.2.1 with Swift 4 and Alamofire 4.0.
["items": <__NSArrayM 0x608000248af0>(
{
currency = USD;
image = "https://cdn.myDomain.com/image.jpg";
"item_title" = "Antique Table";
"name:" = "";
price = 675;
},
{
currency = USD;
image = "https://cdn.mydomain.com/image2.jpg";
"name:" = "";
price = 950;
...
Here is my code. I have tried to get an array r dictionary from the results but it's always nil.
Alamofire.request(myURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.mutableContainers) as! [String: Any]
print(readableJSON)
}
catch {
print(error)
}
}
I have tried this let item = readableJSON["items"] as? [[String: Any]] as suggested here but it would not compile with an error [String:Any] has no subscript and let item = readableJSON["items"] as? [String: Any]! compiles with a warning Expression implicitly coerced from string but produces nil. Parsing this json is life or death for me.
Do something like
let responseJSON = response.result.value as! [String:AnyObject]
then you'll be able to access elements in that dictionary like so:
let infoElementString = responseJSON["infoElement"] as! String
This was the parse json function I eventually came up with. The problem for this json data is that it is a dictionary inside an array. I am a noob and most of the answers and how tos I saw would not fit my json data. Here is the function I finally came up with with worked.
var myItems = [[String:Any]]()
then in my view controller class
func loadMyItems() {
Alamofire.request(myItemsURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.collectionView.reloadData()
})
}
func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.allowFragments) as! [String: Any]
let items = readableJSON["items"] as! [[String: Any]]
self.myItems = items
}
catch {
print(error)
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? myCell
let dictionary = myItems[indexPath.row] as [String:Any]
if let item_title = dictionary["item_title"] as? String {
cell!.textLabel.text = item_title
print(item_title)
}
return cell!
}
Alamofire Example in Swift 3
1.First of all Use two cocoapods to your project.Use SwiftyJSON for json parse
pod 'Alamofire'
pod 'SwiftyJSON'
My Json is below
{"loginNodes":[{"errorMessage":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
It may be done in different way. But I have done below Way. Note if you don't need any parameter to send the server then remove parameter option. It may work post or get method. You can use any way. My Alamofire code is below...which is working fine for me......
Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in
if((responseData.result.value != nil)){
let jsonData = JSON(responseData.result.value)
if let arrJSON = jsonData["loginNodes"].arrayObject {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
let errorCode = aObject["errorCode"] as? String;
let errorMessage = aObject["errorMessage"] as? String;
if("0"==errorCode ){
//Database Login Success Action
}else{
// //Database Login Fail Action
}
}
}
}
}
If You use Like table View Or Collection View or so on, you can use like that..
Declare A Array
var arrRes = [String:AnyObject]
Assign the value to array like
if((responseData.result.value != nil)){
// let jsonData = JSON(responseData.result.value)
if((responseData.result.value != nil)){
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["loginNodes"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tableView.reloadData()
}
}
}
In taleView, cellForRowAt indexPath , Just use
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customCell
cell.errorLabelName.text = arrRes[indexPath.row]["errorMessage"] as? String
Swift 3
Alamofire Example in Swift 3
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
var array = [[String:AnyObject]]()
#IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request("http://www.designer321.com/johnsagar/plumbingapp/webservice/list_advertise.php?zip=123456").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil)
{
let swiftyJsonVar = JSON(responseData.result.value!)
print("Main Responce")
print(swiftyJsonVar)
}
if let result = responseData.result.value
{
if let Res = (result as AnyObject).value(forKey: "response") as? NSDictionary
{
if let Hallo = (Res as AnyObject).value(forKey: "advertise_list") as? NSArray
{
print("-=-=-=-=-=-=-")
print(Hallo)
self.array = Hallo as! [[String:AnyObject]]
print(self.array)
}
}
self.tableview.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
var dict = array[indexPath.row]
cell.lbl1.text = dict["address"] as? String
cell.lbl2.text = dict["ad_created_date"] as? String
cell.lbl3.text = dict["phone_number"] as? String
cell.lbl4.text = dict["id"] as? String
cell.lbl5.text = dict["ad_zip"] as? String
let imageUrlString = dict["ad_path"]
let imageUrl:URL = URL(string: imageUrlString as! String)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
cell.img.image = UIImage(data: imageData as Data)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100
}
}