reload table data in swift3 - json

My screen consist of add and delete buttons, if I clicked add button then it opens popup screen and I entered fields and clicked on save button on the popup screen then data is added, if I close the popup screen then the table is not reloaded. please check my code as shown below.
class EditTest: UIViewController , UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var position = [AnyObject]()
var company = [AnyObject]()
var location = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
loadJsonData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return position.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! customCell
cell.position.text = position[indexPath.row] as? String
cell.company.text = company[indexPath.row] as? String
cell.location.text = location[indexPath.row] as? String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
PopupController
.create(self)
.customize(
[
.animation(.slideUp),
.scrollable(false),
.backgroundStyle(.blackFilter(alpha: 0.7))
]
)
.didShowHandler { popup in
print("showed popup!")
}
.didCloseHandler { _ in
print("closed popup!")
}
.show(DeleteRow.instance())
}
#IBAction func newExp(_ sender: Any) {
PopupController
.create(self)
.customize(
[
.animation(.slideUp),
.scrollable(false),
.backgroundStyle(.blackFilter(alpha: 0.7))
]
)
.didShowHandler { popup in
print("showed popup!")
}
.didCloseHandler { _ in
print("closed popup!")
}
.show(AddRow.instance())
}
func loadJsonData() {
let url = URL(string: "https://url..../id")
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData,timeoutInterval: 10000)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:AnyObject]] {
print(jsonData)
for item in jsonData {
if let pos = item["Position"] as? AnyObject{
self.position.append(pos)
}
if let comp = item["Company"] as? AnyObject{
self.company.append(comp)
}
if let location = item["Location"] as? AnyObject{
self.location.append(location)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
} catch let error as NSError {
print(error)
}
}.resume()
}
}
In the above code, what changes I do to update table data when I close the popup.
func saveMethod(sender:UIButton){
let paramaters = ["Id": id,
"Position": pos,
"Company": com,
"Location": loc] as [String : Any]
let url = URL(string: “https://———/save”)!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: paramaters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
DispatchQueue.main.async {
// now update UI on main thread
let alert = UIAlertController(title: “Row”, message: "Created Successfully", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: { _ -> Void in
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
alert.addAction(OKAction)
self.present(alert, animated: true){}
}
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

Related

Can't get data from rest API to load on ViewDidLoad

I'm new to swift and I can't get my head around this issue.
I can successfully make JSON fetch from an API, but data on the Table View only load after I click a button. Calling the same function on the viewDidLoad didn't load the data when the app is opening.
I tried lot of solutions, but I can't find where the fault is
here's the main view controller code:
import UIKit
struct ExpenseItem: Decodable {
let name: String
let amount: String
let id: String
let timestamp: String
let description: String
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBAction func fetchData(_ sender: Any) {
ds()
self.eTW.reloadData()
}
#IBOutlet weak var eTW: UITableView!
var allExpenses = [ExpenseItem]()
let expensesURL = "https://temp.cuttons.com/json/expenses.json"
override func viewDidLoad() {
super.viewDidLoad()
eTW.delegate = self
eTW.dataSource = self
ds()
self.eTW.reloadData()
}
func parseJSON(data: Data) -> [ExpenseItem] {
var e = [ExpenseItem]()
let decoder = JSONDecoder()
do {
e = try decoder.decode([ExpenseItem].self, from: data)
} catch {
print(error.localizedDescription)
}
return e
}
func ds() {
if let url = URL(string: expensesURL){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, session, error) in
if error != nil {
print("some error happened")
} else {
if let content = data {
self.allExpenses = self.parseJSON(data: content)
}
}
}
task.resume()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allExpenses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = eTW.dequeueReusableCell(withIdentifier: "expense", for: indexPath) as! myCellTableViewCell
cell.name.text = self.allExpenses[indexPath.row].name
if let am = Double(self.allExpenses[indexPath.row].amount) {
if (am > 0) {
cell.amount.textColor = .green
} else {
cell.amount.textColor = .red
}
}
cell.amount.text = self.allExpenses[indexPath.row].amount
return cell
}
thanks
L.
You have to reload the table view after receiving the data asynchronously.
Remove the line in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
eTW.delegate = self
eTW.dataSource = self
ds()
}
and add it in ds
func ds() {
if let url = URL(string: expensesURL) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
print("some error happened", error)
} else {
self.allExpenses = self.parseJSON(data: data!)
DispatchQueue.main.async {
self.eTW.reloadData()
}
}
}
task.resume()
}
}
Do not reload data after the api call in viewDidLoad(). Do it inside of the completion block after you parse the JSON into the object you need (assuming it's successful like you said).
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, session, error) in
guard error == nil else {
print("some error happened")
return
}
guard let data = data else {
print("bad JSON")
return
}
self.allExpenses = self.parseJSON(data: data)
DispatchQueue.main.async {
self.eTW.reloadData()
}
}
task.resume()
Also, use guard let instead of if let if possible.

I'm having troubles displaying an image from JSON in a Table View

I'm trying to display images that comes from an API. The images are inside an URL and I want to fill a Table View with all the array, but it shows only one image at the Table View.
Here's my code:
struct Autos {
let Marca:String
let Modelo:String
let Precio:String
let RutaImagen:String
init?(_ dict:[String:Any]?){
guard let _dict = dict,
let marca=_dict["Marca"]as?String,
let modelo=_dict["Modelo"]as?String,
let precio=_dict["Precio"]as?String,
let rutaImagen=_dict["RutaImagen"]as?String
else { return nil }
self.Marca = marca
self.Modelo = modelo
self.Precio = precio
self.RutaImagen = rutaImagen
}
}
var arrAutos = [Autos]()
func getImage(from string: String) -> UIImage? {
// Get valid URL
guard let url = URL(string: string)
else {
print("Unable to create URL")
return nil
}
var image: UIImage? = nil
do {
// Get valid data
let data = try Data(contentsOf: url, options: [])
// Make image
image = UIImage(data: data)
}
catch {
print(error.localizedDescription)
}
return image
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell
let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let dataResponse = data, error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})
DispatchQueue.main.async {
// Get valid string
let string = self.arrAutos[indexPath.row].RutaImagen
if let image = self.getImage(from: string) {
// Apply image
cell.imgCar.image = image
}
cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
return cell
}
The JSON serialization is working fine, because the other data is showed correctly at the table view, the issue is with the image, because in the table view only appears one image, the other rows are empty. Does anyone have an advise?
I think you should download your full data before loading tableview and reload tableview in the completion handler. Call loadData() method in your viewDidLoad().
fileprivate func loadData() {
let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!
let task = URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let dataResponse = data, error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
For loading images in tableView cell, download the image in background thread and then update the imageView in the main thread.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell
// Get valid string
let string = self.arrAutos[indexPath.row].RutaImagen
//print(string)
cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
let url = URL(string: string)
if url != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if data != nil {
cell.imgCar.image = UIImage(data:data!)
}
}
}
}
return cell
}
Hope this will work.

How to pushViewController from collectionView didSelectItemAt indexPath according to json id(means indexPath should match with json id) in Swift

My home Viewcontroller contains collectionView with items. generally when we click on any of item in collection view then we can push to other viewController by using didSelectItemAt indexPath. but here i am getting the each item image url along with its id from Json and in other viewController for each home id i am getting seperate url with oter fields form Json. when home id and other viewcontroller id matches then i need to push to that viewContoller using didSelectItemAt indexPath in home Viewcontroller.
Here is my code:
Home json:
"financer": [
{
"id": "45",
"icon": "https://emi.com/Star/images/LSPUBLICSCHOOL_icon.png",
"tpe": "L S PUBLIC SCHOOL",
}
{
"id": "2",
"icon": "https://emi.com/Star/images/MC_icon.png",
"tpe": "MC",
}
.
.
HomeVC code:
import UIKit
struct JsonData {
var iconHome: String?
var typeName: String?
init(icon: String, tpe: String) {
self.iconHome = icon
self.typeName = tpe
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var idArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
collectionView.delegate = self
collectionView.dataSource = self
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
layout.itemSize = CGSize(width: 95, height: 95)
collectionView?.collectionViewLayout = layout
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
if let url = NSURL(string: aData.iconHome ?? "") {
if let data = NSData(contentsOf: url as URL) {
cell.paymentImage.image = UIImage(data: data as Data)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
let indexPathHome = indexPath.row
print("home collectionItem indexpath \(indexPathHome)")
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.emi.com/webservice/emi/getfinancer"
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{
DispatchQueue.main.async {
self.activityIndicator.startAnimating()
}
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
print("the home json is \(jsonObj)")
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
let type = financer["tpe"] as! String
self.itemsArray.append(JsonData(icon: pic ?? "", tpe: type))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
}
}).resume()
}
}
otherVC Json:
for id 2 from home getting below json. for id 45 i am getting another json. if if home id 2 and other vcs id 2 matches then this fields need to display if id 45 matches then need to say will update soon message to display.
{
"loan_details": {
"id": "2",
"emi_amount": "1915",
"financer": "4",
}
Code;
import UIKit
class MakePaymentViewController: UIViewController {
#IBOutlet weak var serviceNumTextField: UITextField!
#IBOutlet weak var serviceNumLabel: UILabel!
#IBOutlet weak var dueamountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func makePaymentButton(_ sender: Any) {
}
func makePaymentService(){
let parameters = ["assessmentNo": Int(serviceNumTextField.text ?? ""),
"id":"2",
] as? [String : Any]
let url = URL(string: "https://dev.emi.com/webservice/emi/getassment_details")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if let response = response {
// print(response)
}
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("the json for make payment \(json)")
let loanDetails = json["loan_details"] as! [String : Any]
let dueAmount = loanDetails["emi_amount"] as? String
DispatchQueue.main.async {
self.dueamountLabel.text = dueAmount
}
}catch{
print("error")
}
}
}).resume()
}
#IBAction func searchBtnTapped(_ sender: Any) {
makePaymentService()
}
}
for each home id i am getting separate json for MakePaymentViewController. if we select on 2nd id image from home then need to display those details in MakePaymentViewController. if we select 45 then those details.
here if i select any home item i am going to MakePaymentViewController and displaying id 2 details only. but i want individual details according to ids.
Please help me in code.
create variable on your second controller
class MakePaymentViewController: UIViewController {
var id = ""
}
while pushing second Controller set the value of id based on selected Cell.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
let selectedJson = financerArray[indexpath.row]
let indexPathHome = indexPath.row
print("home collectionItem indexpath \(indexPathHome)")
nextViewController.id = selectedJson["id"]
self.navigationController?.pushViewController(nextViewController, animated: true)
}
pass value of Id to api.
func makePaymentService(){
let parameters = ["assessmentNo": Int(serviceNumTextField.text ?? ""),
"id": id,
] as? [String : Any]
let url = URL(string: "https://dev.emi.com/webservice/emi/getassment_details")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if let response = response {
// print(response)
}
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("the json for make payment \(json)")
let loanDetails = json["loan_details"] as! [String : Any]
let dueAmount = loanDetails["emi_amount"] as? String
DispatchQueue.main.async {
self.dueamountLabel.text = dueAmount
}
}catch{
print("error")
}
}
}).resume()
}

How do I download json file from remote saver and save to bundle for offline access

I am able to download a json file from a server and put it into a TableView each time the App is opened. (see code below)
However, I also want to allow offline access using the last file downloaded. So essentially I am having trouble working out how to save the downloaded file for local access offline. Any help (especially examples) much appreciated.
class KalkanTableController: UITableViewController {
var TableData:Array< String > = Array < String >()
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json")
if let path = Bundle.main.path(forResource: "kalkanInfoTest", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
do {
let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
} catch {}
} catch {}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let item_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let item_obj = item_list[i] as? NSDictionary
{
if let item_name = item_obj["kalkanInfo"] as? Stri
{
TableData.append(item_name)
print(item_name)
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
return
})
}
}
You can try to save your json locally using these methods to save on disk
override func viewDidLoad() {
super.viewDidLoad()
if readKalkanDataFromDisk() {
extract_json(readKalkanDataFromDisk())
} else {
get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json")
}
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
saveKalkanDataOnDisk(kalkanData: data!)
self.extract_json(data!)
})
task.resume()
}
func saveKalkanDataOnDisk(kalkanData: Data) {
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("Kalkan.json")
try kalkanData.write(to: fileURL, options: .atomic)
} catch { }
}
func readKalkanDataFromDisk() -> Data? {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent("Kalkan.json").path
if FileManager.default.fileExists(atPath: filePath), let data = FileManager.default.contents(atPath: filePath) {
return data
}
return nil
}

JSON parsing swift 3

if statusCode == 200 {
let json = response.result.value as? NSDictionary
print("JSON FILE")
//print(json)
let companies = json?["companies"] as? [AnyObject]
print(companies)
for value in companies! {
let address = value["address"] as? String
print(address)
let schedule = companies?["schedule"] as? [AnyObject]// as? NSDictionary
print(schedule)
for sch in schedule! {
}
}
}
Here json file
{
"code": "200",
"message": "OK",
"companies": [
{
"id": "1",
"img": "doxsun.jpg",
"schedule": [
{
"id": "1",
"company_id": "1",
"day": "0",
"time_from": "06:00:00",
"time_to": "23:00:00"
}
]
},
{
"id": "2",
"img": "zalypa.jpg",
"schedule": []
}
]
}
I have a problem with json file parsing how correctly parse it? I can't parse schedule. How to convert all this types? words to pass quality. words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.
There are some conversion issues with correct types using as operator. I believe the below code should allow you to iterate through schedules of each company:
if let JSON = response.result.value as? [String: AnyObject] {
if let companies = JSON["companies"] as? [[String: AnyObject]] {
for company in companies {
if let schedules = company["schedule"] as? [[String: AnyObject]] {
for schedule in schedules {
// do something with the schedule
}
}
}
}
}
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return 2 //datamodel.count
return newarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tblCell.identifier, for: indexPath) as! tblCell
self.json = newarr.object(at: indexPath.row) as! NSDictionary
cell.lblName.text = json.value(forKey: "artistName") as? String
return cell
}
}
extension ViewController {
func swiftyJson(){
let url = URL(string: "https://itunes.apple.com/search?term=jack+johnson")
//let url = URL(string: "http://makani.bitstaging.in/api/business/businesses_list")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
let data = response.result.value as! NSDictionary
self.newarr = data.value(forKey: "results")as! NSArray
print(self.newarr)
self.tblView.reloadData()
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
}
let url = URL(string: "https://api.androidhive.info/contacts")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
if let dicData = response.result.value as? [String : Any]{
if let arrOfCartDetails = Mapper<BaseDataModel>().map(JSON: dicData) {
self.arrData.append(arrOfCartDetails)
print(self.arrData)
if self.arrData.count > 0{
self.arrContect = self.arrData[0].contacts!
print(self.arrContect[0].phone?.home)
}
if self.arrContect.count > 0{
self.tblDemo.reloadData()
}
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
let url = URL(string: "https://jsonplaceholder.typicode.com/todos")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
if let data = response.result.value as? [[String : Any]]{
if Mapper<DocumentDataModel>().mapArray(JSONArray: data).count > 0{
self.arrDataModel = Mapper<DocumentDataModel>().mapArray(JSONArray: data)
print(self.arrDataModel)
let banner = self.arrDataModel[0]
print("userId", banner.userId)
if self.arrDataModel.count > 0{
self.tblDemo.reloadData()
}
}
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
let url = "https://reqres.in/api/products"
AF.request(url, method: .get, parameters: nil).responseJSON{ (response) in
switch(response.result) {
case .success(let responseString):
print("Success")
// print(responseString)
let User = Mapper<Response>().map(JSONObject:responseString)
// print(User)
self.arrayFavouriteJobList = (User?.data)!
print(self.arrayFavouriteJobList)
self.tblData.reloadData()
break
case .failure(_):
print(response.error as Any)
break
}
}
func apiCalling(){
let url = "https://jsonplaceholder.typicode.com/posts"
AF.request(url, method: .get, parameters: nil, headers: nil).responseJSON { (response) in
if let responseData = response.data{
print(response)
do{
let decodeJson = JSONDecoder()
decodeJson.keyDecodingStrategy = .convertFromSnakeCase
self.responseData = try decodeJson.decode([DataModel].self, from: responseData)
self.tblData.reloadData()
}catch{
}
}
}
}
Alamofire.request(url, method: .get, headers: nil).responseJSON{response in
switch response.result{
case.success:
print("sucess")
if let JSON = response.result.value
{
self.hk = JSON as! NSDictionary
print(self.hk)
print(((self.hk.value(forKey: "contacts")as! NSArray).object(at: 4 )as! NSDictionary).value(forKey: "name")as! NSString)
self.flag = 1
self.tbl1.reloadData()
}
case.failure(let Error):
print("error\(Error)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if flag == 0
{
return 0
}
else
{
return (self.hk.value(forKey: "contacts")as! NSArray).count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tbl1.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! TableViewCell1
cell.lbl1.text = (((self.hk.value(forKey: "contacts")as! NSArray).object(at: indexPath.row)as! NSDictionary).value(forKey: "name")as!String)
return cell
}
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
var hk : NSDictionary = NSDictionary()
let url = "https://itunes.apple.com/search?term=jack+johnson"
#IBOutlet var tblview: UITableView!
var flag = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
getdata()
}
func getdata()
{
//let url = "https://itunes.apple.com/search?term=jack+johnson"
Alamofire.request(url, method: .get, headers: nil).responseJSON{response in
switch response.result{
case.success:
print("sucess")
if let JSON = response.result.value
{
self.hk = JSON as! NSDictionary
print(self.hk)
print(((self.hk.value(forKey: "results")as! NSArray).object(at: 0)as! NSDictionary).value(forKey: "artworkUrl60")as! NSString)
//print(((self.hk.value(forKey: "contacts")as! NSArray).object(at: 4 )as! NSDictionary).value(forKey: "name")as! NSString)
self.flag = 1
self.tblview.reloadData()
}
case.failure(let Error):
print("error\(Error)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if flag == 0
{
return 0
}
else
{
return (self.hk.value(forKey: "results")as! NSArray).count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! TableViewCell1
let imageURL = NSURL(string: (((self.hk.value(forKey: "results")as! NSArray).object(at: indexPath.row) as! NSDictionary).value(forKey: "artworkUrl60") as! String))
let imagedData = NSData(contentsOf: imageURL! as URL)!
cell.img1.image = UIImage(data: imagedData as Data)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let bh = storyboard?.instantiateViewController(withIdentifier: "imageViewController")as!imageViewController
bh.str = (((self.hk.value(forKey: "results")as! NSArray).object(at: indexPath.row) as! NSDictionary).value(forKey: "artworkUrl60") as! String)
self.navigationController?.pushViewController(bh, animated: true)
}
// swifty Json
func jsonParsing(){
let url = URL(string: "https://api.androidhive.info/contacts/")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do{
let json = JSON(data:data)
let contacts = json["contacts"][5]["phone"].dictionaryValue
print(contacts)
}
catch{
print(error.localizedDescription)
}
}.resume()
}
func jsonParsing(){
let url = URL(string: "https://api.androidhive.info/contacts/")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do{
let json = JSON(data:data)
let contacts = json["contacts"]
let name = contacts["name"]
for arr in contacts.arrayValue{
print(arr["name"])
}
//prinerrrr)
}
catch{
print(error.localizedDescription)
}
}.resume()
}
}