I want to show data in table cells
now I want show data from api to table cell view on the screen
The output of this api link which is showing in console:
this is struct variable
struct Team: Codable{ //here is struct veriables
var api_id: Int
var id: Int
var first_team:Int
var second_team:Int
var date: String }
here is Im getting data from api
guard let url = URL(string: "http://127.0.0.1:8000/api/matches") else {return}
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 {
//here dataResponse received from a network request
let decoder = JSONDecoder()
let model = try decoder.decode([Team].self, from:
dataResponse) //Decode JSON Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
here is want to use data and show on screen
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TeamCell", for: indexPath) as! TeamTableViewCell
//I want to show here data
return cell
}
Create a global variable for storing teams
var teams = [Team]()
Replace
let model = try decoder.decode([Team].self, from:
dataResponse) //Decode JSON Response Data
with
teams = try decoder.decode([Team].self, from:
dataResponse) //Decode JSON Response Data
tableView.reloadData()
And then,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TeamCell", for:
indexPath) as! TeamTableViewCell
if let team = teams[indexPath.row] {
cell.firstTeamLabel.text = "\(team.first_team)"
cell.dateLabel.text = team.date
...
// Note: Replace label names with your actual one.
}
return cell
}
Related
I am using an endpoint that returns a JSON as response. The problem is response json is a huge data to process for me. From that I want to show all the Surah(englishName) name to display in the tableview. I tried my best as a new bee to iOS development. Please take a look at my snippet and let me know where i am doing wrong.
my Json data here:
ViewController code:
var surahName = [Surah]()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: JSON parse
func parseJSON() {
let url = URL(string: "https://api.alquran.cloud/v1/quran/ar.alafasy")
guard url != nil else{
print("URL Founr Nill")
return
}
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil && data != nil{
do{
self.surahName = try JSONDecoder().decode([Surah].self, from: data!)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch{
print(error)
}
}
}.resume()
}
//MARK: Tableview delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return surahName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:QuranAudioCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuranAudioCell
let arrdata = surahName[indexPath.section].data.surahs
cell.nameLbl.text = arrdata[indexPath.row].englishName
return cell
}
Problem is its not printing anything in the tablview.
Change first line as
var surahNames = [EnglishName]()
Inside do-catch block change
self.surahName = try JSONDecoder().decode([Surah].self, from: data!)
into
let response = try JSONDecoder().decode(Surah.self, from: data!)
self.surahName = response.data.surahs
Now inside cellForRowAtIndexPath do this
let surah = surahName[indexPath.row]
cell.nameLbl.text = surah.englishName
I can't figure out why the cells don't return with data.
I can parse normally using the Decodable, which means that is working.
I've been trying all the methods I find without success.
struct MuscleGroup: Decodable {
let ExcerciseID: String
let description: String
let excerciseName: String
let muscleGroup: String
}
class ExerciseListViewController: UITableViewController {
var muscleGroup = [MuscleGroup]()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return muscleGroup.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseList", for: indexPath) as! ExcerciseList
let muscle = muscleGroup[indexPath.row]
cell.textLabel!.text = muscle.excerciseName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.muscleGroup[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
getJson()
}
func getJson(){
guard let url = URL(string: "https://jsonurl") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
for muscle in muscles {
let muscleGroup = muscle.excerciseName
print(muscleGroup)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print(error)
}
}
}.resume()
}
If I change the var muscleGroup = String to ["Chest", "Back", "Abdominals","Arms", "Legs"] it returns correctly.
Also, the print result on the console returns all the data that needs to be on the Table View.
What am I doing wrong?
As you probably want to use the entire struct
Replace
var muscleGroup = [String]()
with
var muscleGroups = [MuscleGroup]()
Replace
let muscles = try JSONDecoder().decode([MuscleGroup].self, from: data)
for muscle in muscles {
let muscleGroup = muscle.excerciseName
print(muscleGroup)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
with
self.muscleGroups = try JSONDecoder().decode([MuscleGroup].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
Replace
cell.textLabel?.text = self.muscleGroup[indexPath.row]
with
cell.textLabel?.text = self.muscleGroups[indexPath.row].muscleGroup
In your getJson function this line
let muscleGroup = muscle.excerciseName
is creating a new local variable called muscleGroup, change the line to be
self.muscleGroup.append(muscle.excerciseName)
i.e. get rid of the let and append the value to the main array variable
Also move the
DispatchQueue.main.async {
self.tableView.reloadData()
}
to be outside of the for loop of muscles as you are forcing the table to reload for each entry rather than when you are finished
I have this here structured:
struct Excercise: Codable {
let excerciseID: String
let excerciseName: String
let description: String
let intensity: Int
}
Then, that's the var:
var excercistList = [Excercise]()
And the cellforrowat:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExcerciseCell", for: indexPath)
cell.textLabel?.text = self.excercistList[indexPath.row].excerciseName
return cell
}
That's the URLSession:
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else{return}
do {
let excerciseList = try JSONDecoder().decode(Excercise.self, from: data)
print(excerciseList.excerciseName)
} catch let jsonErr {
print("Error", jsonErr)
}
}.resume()
I get the right results on the print, but nothing on the table.
What am I doing wrong?
first of all you have to populate your dataSource which is var excercistList = [Excercise](). After that you have to reload tableView.
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else{return}
do {
let excerciseListFromDecoder = try JSONDecoder().decode(Excercise.self, from: data)
self.excercistList = excerciseListFromDecoder
self.tableView.reloadData()
} catch let jsonErr {
print("Error", jsonErr)
}
}.resume()
You have to be sure that you have set correctly
tableView.delegate = self
tableView.dataSource = self
and the numberOfRowsInSection
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.excercistList.count
}
So I am trying to add some data returned from a function and I can only access that data from inside that function so I ended up putting the table inside the function but after I did so I received the error above.
Any ideas?
This is my code:
import Foundation
import UIKit
class UserAccView: UIViewController , UITableViewDataSource {
#IBAction func GetUserInfo(_ sender: UIButton) {
guard let url = URL(string: "https://goollyapp.azurewebsites.net/api/v0.1/Goolly/User/218910182109") else{return}
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print (response)
}
if let data = data {
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard let data_array = json as? NSArray else
{
return
}
for i in 0 ..< data_array.count
{
if let data_object = data_array[i] as? NSDictionary
{
if let Body = data_object["id"] as? String,
let InfoId = data_object["TransDate"] as? String,
let Title = data_object["Debt"] as? String,
let UserId = data_object["Crdit"] as? String,
let InfoType = data_object["Desc"] as? String
{}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (data?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel?.text = "cells"
return cell
}
}.resume()
}
}
Why you have added the dataSource methods inside your Api Call ? Write those methods outside of your GetUserInfo IBAction.
Secondly, now you want to reload the tableview. For that create IBOutlet for tableview first and when response comes from the api you can reload the tableview after filling the response in your data array.
Lastly don't use var cell = UITableViewCell() like this in cellForRowAt. It will freeze your tableview . Use it like this
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell.
Hope it helps you
I'm trying to connect my swift ios app to mysql with php... and the upon receiving the JSON from the php.. i converted it into nsarray and tried to populate my tableview with it.. however it doesnt seem to show anything in the tableview when i run it.... the data is successful in passing into the NSArray as i see my result when i print(values).. it just cant seem to show up on my tableview and i dont know why
#IBOutlet weak var tableView: UITableView!
var values:NSArray = []
#IBAction func php(_ sender: Any) {
let url = NSURL(string: "http://localhost/try.php")
let data = NSData(contentsOf: url! as URL)
values = try! JSONSerialization.jsonObject(with: data! as Data, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
print (values)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.descriptionView.text = (values[indexPath.row] as AnyObject) as? String
return cell
}
That's the recommended way to load data over the network.
As mentioned in the comment do not use NSArray, NSData and NSURL in Swift 3. URLSession loads the data asynchronously and in the background. The table view is reloaded on the main thread.
var values = [[String:String]]()
#IBAction func php(_ sender: AnyObject) {
let url = URL(string: "http://localhost/try.php")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
self.values = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String:String]]
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
task.resume()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
let item = values[indexPath.row]
cell.descriptionView.text = item["title"]
return cell
}