JSON parsing swift 3 - json

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()
}
}

Related

How to push different view controller from collection view didSelectItemAt based on Json id in swift

My project contains collectionView.. but how to push different viewcontroller from didSelectItemAt based on json id.. and i have separate vewcontrollers for each id.. but i am unable to push different viewcontrolls with didSelectItemAt based on json id.
here is my Json for collectionView:
{
"financer": [
{
"id": "45",
"icon": "https://hello.com//images/img1.png"
}
{
"id": "40",
"icon": "https://hello.com//images/img2.png"
}
.
.
.
]
}
here is my home collectionview code:
import UIKit
struct JsonData {
var iconHome: String?
init(icon: String, tpe: String) {
self.iconHome = icon
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var idArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
//Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
}
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 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.com/webservices/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
print("home financer id \(id)")
self.idArray.append(id)
print("the home financer idsArray \(self.idArray.append(id))")
self.itemsArray.append(JsonData(icon: pic ?? ""))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
when I click on any item from collectionview i am able to push same view controller but i need to push different view controller based on json id. i dont know how to and where to use json id to push differnt viewcontroller using didselectItem atIndexPath. anyone please help me here.
Update your homeServiceCall function
func homeServiceCall(){
let urlStr = "https://dev.com/webservices/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
self.itemsArray.append(JsonData(icon: pic ?? ""))
self.idArray.append(id)
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
Create a string property called financerId in your MakePaymentViewController
In your didSelect function
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as? MakePaymentViewController {
nextViewController.finacerId = idArray[indexPath.row]
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
Update
for financer in financerArray {
if let id = financer["id"] as? Int {
self.idArray.append(id)
}
if let pic = financer["icon"] as? String {
elf.itemsArray.append(JsonData(icon: pic))
}
}

Parse the json value and get ID into var in Swift

I have list of company names with IDs. I have used a drop down and showing company name in it by parsing JSON data. uncertainly I am unable to get the ID of the selected item in the drop down menu.
My json data is
{
"success": true,
"message": [
{
"company_name": "ABC",
"id": 1
},
{
"company_name": "JHG",
"id": 10
}
]}
My swift code:
let url = NSURL(string: COMPANY_URL)
URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
// print(jsonObj.value(forKey: "message")!)
if let messageArray = jsonObj.value(forKey: "message") as? NSArray
{
for message in messageArray
{
if let messageDict = message as? NSDictionary
{
if let data = data {
let successmessage = jsonObj.value(forKey: "success") as? Int
if(successmessage == 1)
{
if let company_name = messageDict.value(forKey: "company_name")
{
self.companiesArray.append(company_name as! String)
}
if let company_id = messageDict.value(forKey: "id")
{
self.companyidstr.append(company_id as! Int)
print(self.companyidstr)
}
for messageArray in self.companyidstr
{
print(messageArray)
let btnlabel = Int(self.companyBtn.titleLabel!.text!)
if(btnlabel == Int(messageArray))
{
self.companyidstring = messageArray
print(self.companyidstring)
// THIS IS WHERE IT NEED TO SHOW ID BUT NOT }
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
} else
{
}
}
}
}
}
}
}).resume()
My requirement is to show list of company name's to users but when they select any company name,should save in the form of concerned ID of the selected item.
my ENTIRE CODE:
class RegistrationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var companyBtn: UIButton!
final let COMPANY_URL = COMPANY_URL
var companiesArray = [String]()
var companyidstr = [Int]()
var companyidstring: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
downloadCompanyNamesFromDB()
// insertUserDetailsintoDB()
tableView.isHidden = true
self.downloadCompanyNamesFromDB()
//tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.delegate = self
}
#IBAction func companyBtnClick(_ sender: Any) {
// tableView.isHidden = false
if(tableView.isHidden)
{
animate(toogle: true)
} else
{
animate(toogle: false)
}
}
func animate(toogle: Bool)
{
if(toogle)
{
UIView.animate(withDuration: 0.3)
{
self.tableView.isHidden = false
}
} else{
UIView.animate(withDuration: 0.3)
{
self.tableView.isHidden = true
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return companiesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = companiesArray[indexPath.row]
print(companiesArray)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let companytitle = companiesArray[indexPath.row]
companyBtn.setTitle(companytitle, for: .normal)
print(companytitle)
// print(companiesArray[indexPath.row].id as! String)
// companiesArray = message --> HERE IS THE CODE
animate(toogle: false)
}
func downloadCompanyNamesFromDB()
{
let url = NSURL(string: COMPANY_URL)
URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
// print(jsonObj.value(forKey: "message")!)
if let messageArray = jsonObj.value(forKey: "message") as? NSArray
{
for message in messageArray
{
if let messageDict = message as? NSDictionary
{
if let data = data {
let successmessage = jsonObj.value(forKey: "success") as? Int
if(successmessage == 1)
{
} else
{
}
}
}
}
}
}
}).resume()
}
}
}
It's better to
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode(Root.self,from:data)
print(res.message)
// MARK: - Empty
struct Root: Codable {
let success: Bool
let message: [Message]
}
// MARK: - Message
struct Message: Codable {
let companyName: String
let id: Int
}
var companiesArray = [Message]()
let url = URL(string: COMPANY_URL)!
URLSession.shared.dataTask(with:url, completionHandler: {(data,response,error) ->
Void in
guard let data = data else { return }
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode(Root.self,from:data)
companiesArray = res.message
print(res.message)
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}).resume()

reload table data in swift3

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()
}

Display images in UITableview

I'm trying to display images from api in the tableview but I get no images or anything. ImageTableViewCell has the outlet to the image only.
import UIKit
import Alamofire
import SwiftyJSON
import Haneke
class SlideViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
#IBOutlet weak var tableview : UITableView!
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
getJSON()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell
let url = URL(string: images[indexPath.row])
cell.images.hnk_setImage(from: url!)
return cell
}
func getJSON() {
let url = "http://localhost:8000/api/hello"
request(url , method: .get, encoding: JSONEncoding.default )
.responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
do{
if let albums = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String: Any],
let pics = albums["pic"] as? [Any] {
self.images = pics as! [String]
for kick in pics {
self.images.append(kick as! String)
}
}
}catch {
print("Error with Json: \(error)")
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
}
}
}
Any help will be appreciated. I tried many methods but this seems to be simple and easy to follow up
Check below code
var images = [String]()
func getJSON() {
let url = "http://localhost:8000/api/hello"
request(url , method: .get, encoding: JSONEncoding.default )
.responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
do{
let albums = try JSONSerialization.jsonObject(with: response.data!, options:.allowFragments) as! [[String: AnyObject]]
print(albums)
if let pics = album["pic"]
{
for album in pics
{
images.append(album)
}
}
}catch {
print("Error with Json: \(error)")
}
self.tableview.reloadData()
}
}
}
Your JSON response is Dictionary not Array and its contains pic array inside of it. So type result of jsonObject(with:options:) to [String:Any] instead of [[String: AnyObject]]
do{
if let albums = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String: Any],
let pics = albums["pics"] as? [Any] {
images = pics.flatMap{ $0 as? String }
}
}catch {
print("Error with Json: \(error)")
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
You must have at least one section to show.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

Hi there , I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data

I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data.
''import UIKit
class
FirstViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{
#IBOutlet weak var tableview: UITableView!
var TableData:Array< String > = Array < String >()
var valueToPass:String!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstViewCell", 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 = NSURLRequest.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 countries_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let country_name = country_obj["country"] as? String
{
if let country_code = country_obj["code"] as? String
{
TableData.append(country_name + " [" + country_code + "]")
}
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
tableview.reloadData()
}
}
you need to set tableView's dataSource and delegate to self.