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
}
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'm new into coding, learning how to parse JSON image into table view
able to display the labels but not able to display the image file. How to display it? I used the code given below please check it.
import UIKit
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var dataArray = [[String:AnyObject]]()
#IBOutlet weak var myTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://jsonplaceholder.typicode.com/photos")! //change the url
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
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 {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {
self.dataArray = json as [[String : AnyObject]]
DispatchQueue.main.async {
self.myTable.reloadData()
}
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
cell.labout.text = String(describing: dataArray[indexPath.row]["id"]!)
cell.imagethum.image = UIImage(named :dataArray[indexPath.row]["thumbnailUrl"]! as! String)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "story") as? FinalViewController
var selectedindex = indexPath.row
vc?.jarray = dataArray
vc?.selectedindex1 = selectedindex
self.navigationController?.pushViewController(vc!, animated: true)
}
}
You need to download your image at first.
The basic solution is:
if let url = URL(string: "YOUR_URL") {
if let data = try? Data(contentsOf: url) {
cell.imagethum.image = UIImage(data: data)
}
}
For more advanced solution take a look on SDWebImage framework ( for example ) - it's beginner-friendly.
You need to download the image using thumbnailUrl String that you're getting from JSON response.
Replace the implementation of cellForRowAt method with the following code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
cell.labout.text = String(describing: dataArray[indexPath.row]["id"] ?? "")
if let urlString = dataArray[indexPath.row]["thumbnailUrl"] as? String, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
cell.imagethum.image = UIImage(data: data)
}
}.resume()
}
return cell
}
Also, don't use forced unwrapping (!) so extensively. It might result in crashing the app unnecessarily.
You can try this
We use this SDWebImage pod to load images from URL. This pod provides an async image downloader with cache support.
Example Of SDWebImage as below
let img1 = savedInspofflineData[indexPath.row].image1
if img1 == ""{
//Error
}else{
let imageUrl = URL(string: img1!)!
cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
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
}
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
Having a problem with this code. Basically i'm trying to populate a table cell using an image im pulling from twitter. The url field here has the value http://pbs.twimg.com/profile_images/796924570150301696/35nSG5nN_normal.jpg but for some reason the print("REACHED") is never printed. Any help/suggestions appreciated!
code snippet:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tIdentifier, for: indexPath) as! TweetCell
let tweet = tweets[indexPath.section][indexPath.row]
let url = tweet.user.profileImageURL!
print(url.absoluteString)
let data = try? Data(contentsOf: url)
if (data == nil){
} else {
print("REACHED")
cell.avatarImage = UIImage(data: data!)
}
cell.tweet = tweets[indexPath.section][indexPath.row]
return cell
}
This worked for me:
func example() {
let cell = UITableViewCell()
let url = URL(string: "http://pbs.twimg.com/profile_images/796924570150301696/35nSG5nN_normal.jpg")
do {
let data = try Data(contentsOf: url!)
print("REACHED")
cell.imageView?.image = UIImage(data: data)
} catch {
print("received this error:\n\(error.localizedDescription)")
}
}
If it doesn't work right away, at least you'll have an error message to help you figure it out. Good luck!
Edit:
You should make sure you have updated your Info.plist to include an entry for:
App Transport Security Settings
Without this you will not have access to other sites.
Transport security has blocked a cleartext HTTP
Some tips for an easy lifeā¦
Don't force unwrap
Don't download on the main queue
Don't expose your cell's IBOutlets
let imageQueue = DispatchQueue(label: "imageQueue", qos: DispatchQoS.background)
class TweetCell: UITableViewCell {
#IBOutlet fileprivate var avatarImage: UIImageView!
var tweet: Tweet {
didSet {
guard let url = tweet.user.profileImageURL else { return }
loadImage(url: url)
}
}
fileprivate func loadImage(url: URL) {
imageQueue.async {
do {
let data = try Data(contentsOf: url)
DispatchQueue.main.async {
self.avatarImage.image = UIImage(data: data)
}
} catch {
// Handle error
}
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tIdentifier, for: indexPath) as! TweetCell
cell.tweet = tweets[indexPath.section][indexPath.row]
return cell
}