How to show image from json in table view - ios

To get data the from json class is created
class getData: NSObject {
var descriptionn : String = ""
var image : String = ""
// static let shared = getData()
func getDataForTableView(results: [[String:String]], index : Int){
var productArray = [String:String]()
productArray = results[index]
descriptionn = productArray["description"]!
image = productArray["images"]!
}
}
To display data in table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell
// if results.count > 0{
classObject.getDataForTableView(results: results, index: indexPath.row)
cell.sneakerImageView.image=filteredsneakernews[indexPath.row].image
print("abc image"+classObject.image)
cell.newsTitle.text = classObject.descriptionn
// }
return cell
}
The json is following foramt
ptional({
data = (
{
"created_date" = "2017-11-09 14:58:58";
"created_on" = "2017-11-09";
"createdd_by" = 3;
description = dfdfdsdfsdfs;
id = 4;
images = "7a53f87882409c4622a0977d5026038b.jpg";
likes = 25;
product = 12;
status = 1;
title = facebook;
"title_keys" = fac;
type = News;
},
{
"created_date" = "2017-11-15 14:33:01";
"created_on" = "2017-11-23";
"createdd_by" = 3;
description = dfdfdf;
id = 7;
images = "e626b8003e6e08df874e33556e7f6e69.jpg";
likes = 3;
product = 0;
status = 1;
title = don;
"title_keys" = don;
type = News;
},
{
"created_date" = "2017-11-16 10:34:48";
"created_on" = "2017-11-13";
"createdd_by" = 3;
description = "my first computer";
id = 8;
images = "556b1855de039b8d99bc787acd103262.jpg";
likes = 90;
product = 13;
status = 1;
title = Dell;
"title_keys" = dell;
type = News;
},
{
"created_date" = "2018-01-02 16:23:54";
"created_on" = "2018-01-08";
"createdd_by" = 3;
description = sdfsdfsfdf;
id = 14;
images = "0c980d3f9cd0393a46bb04995d16177a.jpg";
likes = 0;
product = 0;
status = 1;
title = dfsfdsfdfs;
"title_keys" = " dfsfdsfdfs";
type = News;
}
);
message = "Success.";
newsurl = "http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/";
success = 1;
})
This json has image of following from
images = "7a53f87882409c4622a0977d5026038b.jpg";
How to display the image .Image(classObject.image) in string format how to display image view on table view ?you can download the code from this link .https://drive.google.com/file/d/1bVQsuSQINSa6YRwZe2QwEjPpU_m7S3b8/view?usp=sharing

Image path should be like URL format. http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/7a53f87882409c4622a0977d5026038b.jpg.
yourJSON
message = "Success.";
newsurl = "http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/";
success = 1;
Global Declaration:
var imgURLStringArr = [String]()
func appendURLPathFromJSON(jsonDict: NSDictionary)
{
let urlPath : String = jsonDict.value(forKey: "newsurl") as! String
let dataArr : NSArray = jsonDict.value(forKey: "data") as! NSArray
for i in 0..<dataArr.count
{
let dataDict : NSDictionary = dataArr[i] as! NSDictionary
let imageStr : String = dataDict.value(forKey: "images") as! String
let appendPath : String = urlPath + imageStr
imgURLStringArr.append(appendPath)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
print("willDisplaywillDisplay")
let cell = cell as! DiscoveryNewsTableViewCell
URLSession.shared.dataTask(with: NSURL(string: self.imgURLStringArr[indexPath.row])! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
cell.thumbImg.image = image
})
}).resume()
}

Related

how to reduce the code in tableView cell in swift

hey i'm in the process of learning to code. I created an app that downloads JSON data - covid.
It looks like this :
enter image description here
my code in function (code below) has become terribly large.
how can I reduce this code?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.covidCell, for: indexPath) as! CovidCell
if inSearchMode == true {
cell.countryLabel.text = filterCovidData[indexPath.row].country
cell.regionLabele.text = filterCovidData[indexPath.row].continent
cell.casesLabel.text = "Case: \(filterCovidData[indexPath.row].cases!)"
cell.deathLabel.text = "Death: \(filterCovidData[indexPath.row].deaths!)"
cell.activelabel.text = "Active: \(filterCovidData[indexPath.row].active!)"
cell.testsLabel.text = "Test: \(filterCovidData[indexPath.row].tests!)"
cell.todayCasesInfo.text = "\(filterCovidData[indexPath.row].todayCases!)"
let imageUrl = filterCovidData[indexPath.row].countryInfo?.flag
fetchImage(withUrlString: imageUrl!) { (image) in
DispatchQueue.main.async {
cell.countryFlag.image = image
}
}
} else {
cell.countryLabel.text = covidData[indexPath.row].country
cell.regionLabele.text = covidData[indexPath.row].continent
cell.casesLabel.text = "Case: \(covidData[indexPath.row].cases!)"
cell.deathLabel.text = "Death: \(covidData[indexPath.row].deaths!)"
cell.activelabel.text = "Active: \(covidData[indexPath.row].active!)"
cell.testsLabel.text = "Test: \(covidData[indexPath.row].tests!)"
cell.todayCasesInfo.text = "\(covidData[indexPath.row].todayCases!)"
let imageUrl = covidData[indexPath.row].countryInfo?.flag
fetchImage(withUrlString: imageUrl!) { (image) in
DispatchQueue.main.async {
cell.countryFlag.image = image
}
}
}
return cell
}
See the repetitive code.
You do the same, except the source of the populate, so, let's just retrieve the model according to your needs (inSearchMode), and then let's call the same code.
let model = inSearchMode ? filterCovidData[indexPath.row] : covidData[indexPath.row]
cell.countryLabel.text = model.country
cell.regionLabele.text = model.continent
cell.casesLabel.text = "Case: \(model.cases!)"
cell.deathLabel.text = "Death: \(model.deaths!)"
cell.activelabel.text = "Active: \(model.active!)"
cell.testsLabel.text = "Test: \(model.tests!)"
cell.todayCasesInfo.text = "\(model.todayCases!)"
let imageUrl = model.countryInfo?.flag
fetchImage(withUrlString: imageUrl!) { (image) in //I'duse a [weak self] here
DispatchQueue.main.async {
cell.countryFlag.image = image
}
}
That's be the first step.
You can have another logic at start:
let arrayToUse = inSearchMode ? filterCovidData : covidData
let model = arrayToUse[indexPath.row]
You can also add a code in CovidCell
func update(model: ModelThatsInsideCovidData) {
countryLabel.text = model.country
regionLabele.text = model.continent
casesLabel.text = "Case: \(model.cases!)"
deathLabel.text = "Death: \(model.deaths!)"
activelabel.text = "Active: \(model.active!)"
testsLabel.text = "Test: \(model.tests!)"
todayCasesInfo.text = "\(model.todayCases!)"
let imageUrl = model.countryInfo?.flag
//Here cell doesn't have that method, should it be accessible?, I'll let you decide.
fetchImage(withUrlString: imageUrl!) { (image) in
DispatchQueue.main.async {
self.countryFlag.image = image
}
}
And then, in cellForRowAt:
let model = ...
cell.update(model: model)
return cell

issue while printing instgram post response on label

I am getting instagram post response but from that i am getting array into object i mean main array is data and in that i ahve object user and in that i want to print full_name Here is response
Response
SUCCESS: {
data = (
{
attribution = "<null>";
caption = {
"created_time" = 1533621008;
from = {
"full_name" = "Mike Alpha";
id = 8376082973;
"profile_picture" = "";
username = mikealpha607;
};
id = 17952863989106568;
text = Hi;
};
comments = {
count = 1;
};
"created_time" = 1533621008;
filter = Normal;
id = "1840468872962982375_8376082973";
images = {
"low_resolution" = {
height = 320;
url = "";
width = 320;
};
"standard_resolution" = {
height = 640;
url = "https://scontent.cdninstagram.com/vp/adcc206df693d4d65c9b6f6b5ef7a016/5C024385/t51.2885-15/sh0.08/e35/s640x640/37867466_267564047306571_7531604489342550016_n.jpg";
width = 640;
};
thumbnail = {
height = 150;
url = "";
width = 150;
};
};
likes = {
count = 2;
};
link = "https://www.instagram.com/p/BmKqLBRH0Hn/";
location = {
id = 761100677398542;
latitude = "23.102652628869";
longitude = "72.595614227203";
name = "PVR Cinemas, Motera, Ahmedabad";
};
tags = (
);
type = image;
user = {
"full_name" = "Mike Alpha";
id = 8376082973;
"profile_picture" = "";
username = mikealpha607;
};
"user_has_liked" = 1;
"users_in_photo" = (
);
}
and i am getting user object but no understand that how to print on label let me show my code
Code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TestTableViewCell
let createdTime = serviceData[indexPath.row]["created_time"]
let timeinterval : TimeInterval = (createdTime as! NSString).doubleValue
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "dd MMM yyyy"
cell.lblDate.text = dateFormater.string(from: dateFromServer as Date)
let instaResponse = serviceData[indexPath.row]["user"]
print(instaResponse) **Here I am getting user object response but i understand how to print on label**
return cell
}
please help me to under stand this
please check this new issue
let imagePosts = serviceData[indexPath.row]["images"] as! [String:Any]
let instaImage = imagePosts["standard_resolution"]
let proimgurl1 = NSURL(string: instaImage as! String)
cell.imgPost.image = UIImage(data: NSData(contentsOf: proimgurl1! as URL)! as Data)
i am geting imageurl but when i pass to image view its going crash
You can try
let instaResponse = serviceData[indexPath.row]["user"] as! [String:Any]
let fName = instaResponse["full_name"] as! String
cell.fnameLbl.text = fName // suppose outlet is fnameLbl
printfName)
//
let imagePosts = serviceData[indexPath.row]["images"] as! [String:[String:Any]]
let instaImage = imagePosts["standard_resolution"]["url"] as! String

Parsing JSON using a Swift Dictionary

I am having a hard time parsing JSON with Swift. I have written a function that make a get request to an api and retrieves the data as JSON and converts it into a dictionary. After that I am trying to use a tableViewController to set each title and subtitle from the values I received from the JSON. I am trying to set the title as the homeTeam and the subtitle as the awayTeam. I do not know much about Swift so I was hoping for some help.
Here is my JSON that is stored in a dictionary:
dictionary = ["scoreboard": {
gameScore = (
{
game = {
ID = 35119;
awayTeam = {
Abbreviation = ATL;
City = Atlanta;
ID = 91;
Name = Hawks;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = CLE;
City = Cleveland;
ID = 86;
Name = Cavaliers;
};
location = "Quicken Loans Arena";
time = "7:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35120;
awayTeam = {
Abbreviation = MIA;
City = Miami;
ID = 92;
Name = Heat;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = TOR;
City = Toronto;
ID = 81;
Name = Raptors;
};
location = "Air Canada Centre";
time = "7:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35121;
awayTeam = {
Abbreviation = NYK;
City = "New York";
ID = 83;
Name = Knicks;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = MEM;
City = Memphis;
ID = 107;
Name = Grizzlies;
};
location = "FedEx Forum";
time = "8:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35122;
awayTeam = {
Abbreviation = DET;
City = Detroit;
ID = 88;
Name = Pistons;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = HOU;
City = Houston;
ID = 109;
Name = Rockets;
};
location = "Toyota Center";
time = "8:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35123;
awayTeam = {
Abbreviation = SAS;
City = "San Antonio";
ID = 106;
Name = Spurs;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = DAL;
City = Dallas;
ID = 108;
Name = Mavericks;
};
location = "American Airlines Center";
time = "8:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35124;
awayTeam = {
Abbreviation = NOP;
City = "New Orleans";
ID = 110;
Name = Pelicans;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = DEN;
City = Denver;
ID = 99;
Name = Nuggets;
};
location = "Pepsi Center";
time = "9:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35125;
awayTeam = {
Abbreviation = MIN;
City = Minnesota;
ID = 100;
Name = Timberwolves;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = UTA;
City = Utah;
ID = 98;
Name = Jazz;
};
location = "Vivint Smart Home Arena";
time = "9:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35126;
awayTeam = {
Abbreviation = OKL;
City = "Oklahoma City";
ID = 96;
Name = Thunder;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = PHX;
City = Phoenix;
ID = 104;
Name = Suns;
};
location = "Talking Stick Resort Arena";
time = "10:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35127;
awayTeam = {
Abbreviation = SAC;
City = Sacramento;
ID = 103;
Name = Kings;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = LAL;
City = "Los Angeles";
ID = 105;
Name = Lakers;
};
location = "Staples Center";
time = "10:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
}
);
lastUpdatedOn = "<null>";
}]
Here is what I have currently for setting my title and subtitle in Swift:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NBAScore", for: indexPath)
// Configure the cell...
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject]
{
if let game = gameScore["game"] as? [String:AnyObject]
{
if let awayTeam = game["awayTeam"] as? String
{
cell.textLabel?.text = awayTeam }
}
}
}
return cell
}
Best will be to create a Struct add variable's for the properties you need after that make an array from that struct parse your array of json using a for loop and append them to the newly array you have created then you can access those properties using dot notation inside your cellForRow function
Use the below code to get the team name -
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject]
{
if let game = gameScore["game"] as? [String:AnyObject]
{
if let awayTeam = game["awayTeam"] as? [String: AnyObject] {
if let teamName = awayTeam["Name"] as? String {
cell.textLabel?.text = teamName
}
}
}
}
}
For that purpose I would use some library that was build to parse JSON dictionaries to some model objects as it's a good practice. E.g. I would recommend Marshal as it's lightweight and easy to use.
You just create a struct or any other Swift structure and then you call Marshal. Later on you use those mapped objects in your tableView dataSource.
Your 'gameScore' object is an array not a dictionary type ([String:AnyObject]). My mistake that i didn't check the json object properly.
First create an array and store all the team name in that array. For Example, I am storing all the awayteam name for now in an array. Check the below code. I didn't run the below source code in my end, Since your json has problem. It's not a valid json data. There is formatting issue. But this below code will work.
let awayTeamArr = NSMutableArray()
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] {
if let gameScore = scoreBoard["gameScore"] as? NSArray {
for gameScoreObj in gameScore {
if let gameObj = gameScoreObj as [String: AnyObject] {
if let game = gameObj["game"] as? [String:AnyObject] {
if let awayTeam = game["awayTeam"] as? [String: AnyObject] {
if let teamName = awayTeam["Name"] as? String {
awayTeam.add(teamName)
}
}
}
}
}
}
}
Then in your tableView delegate method for each cell display the object of that specific index of 'awayTeamArr' object. If this answer worked then make the question as completed.
I was able to figure out an answer to my own question. The "gameScore" key of the dictionary was giving me trouble because I was type casting it incorrectly. It was an Array<[String:Any]> not a dictionary.
func parseJSON(){
var s = nbaScore()
var i = 0
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
// Could check the lastUpdattedOn date before doing the following:
if let gameScore = scoreBoard["gameScore"] as? Array<[String:Any]>
{ //Loop for # of games
//while gameScore[i]["game"] as? [String:Any] != nil
while i < gameScore.count
//for _ in (gameScore[0]["game"] as? [String:Any])!
{
// An array of dictionaries
if let game = gameScore[i]["game"] as? [String:Any]
{
s.gameTime = (game["time"] as? String)!
if let awayTeam = game["awayTeam"] as? [String:Any]
{
s.awayTeamCity = (awayTeam["City"] as? String)!
s.awayTeamName = (awayTeam["Name"] as? String)!
}
if let homeTeam = game["homeTeam"] as? [String:Any]
{
s.homeTeamCity = (homeTeam["City"] as? String)!
s.homeTeamName = (homeTeam["Name"] as? String)!
}
}
if let isUnplayed = gameScore[i]["isUnplayed"] as? String
{
s.isUnplayed = isUnplayed
}
if let isInProgress = gameScore[i]["isInProgress"] as? String
{
s.isInProgress = isInProgress
}
if let isCompleted = gameScore[i]["isCompleted"] as? String
{
s.isCompleted = isCompleted
}
if let awayScore = gameScore[i]["awayScore"] as? String
{
s.awayTeamScore = awayScore
}
if let homeScore = gameScore[i]["homeScore"] as? String
{
s.homeTeamScore = homeScore
}
i += 1
scores.append(s)
s.clearData()
gamesCount += 1
}
}
}
}

How to iterate through Dictionary of Dictionary Values in UITableViewCell?

This is my first post and I hope its a great question because iv been stuck on this for days. (Literally searched every related question and found nothing that I could add up for a solution.)
Basically I'm building a pure Swift application. My problem is that I cant figure out how to place each dictionary values into each UITableCell that is created.
Also the JSON response from the GET creates a NSCFDictionary type.
UITableViewCell Properties
UILabel - Holds the Offer "name"
UI Label #2 - Holds Offer "description"
UIImage - Holds the Offer "thumb_url"
So basically I need to store each offer object's (name, description, thumb_url) in every UITableViewCell that the ViewController creates.
GET Request
import UIKit
class freeIAPCell: UITableViewCell {
#IBOutlet weak var aName: UILabel!
#IBOutlet weak var aDescription: UILabel!
#IBOutlet weak var aImage: UIImageView!
}
class FreeIAPViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Everbadge Request
var apiURL = "apiurlhere"
var parsedArray: [[String:String]] = []
func queryEB() {
// Query DB Here
// Store the API url in a NSURL Object
let nsURL = NSURL(string: apiURL)
let request = NSMutableURLRequest(URL: nsURL!)
request.HTTPMethod = "GET"
// Execute HTTP Request
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
data, response, error in
if error != nil {
print("Error = \(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
print(json.isKindOfClass(NSDictionary)) // true
let data = json.objectForKey("data") as! NSDictionary
//print(data)
let m = data.objectForKey("offers") as! NSArray
print(m)
print(m.valueForKeyPath("name"))
self.parsedArray = m as! [[String : String]]
} catch {
print("THERE WAS AN ERROR PARSING JSON FOR EVERBADGE")
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
queryEB()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
// MARK: UITableView method implementation
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("freeAppCell", forIndexPath: indexPath) as! freeIAPCell
let obj = parsedArray[indexPath.row] // fatal error: Index out of range
cell.aName.text = obj["name"]
return cell
}
}
API Request Data Structure (print(m))
(
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
{
"name" = "Mate";
id = 23941;
description = "10-20 word description goes here"
"url" = "google.com
"ver" = "0.12"
price = "0.17"
"public_name" = "Good Ole Mate"
"thumb_url" = "http://google.com/mate.jpg
};
);
First create public arrays for your 3 items...
var nameArray = [String]()
var descriptionArray = [String]()
var thumbnailArray = [String]()
Then loop through your json parse like this....
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! NSDictionary
if responseString != nil
{
let items: AnyObject! = responseString["items"] as AnyObject!
if items != nil
{
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i
{
if let names = items[i]["name"] as? NSDictionary
{
let name = names as! String
self.nameArray.append(name)
}
if let descriptions = items[i]["description"] as? NSDictionary
{
let description = descriptions as! String
self.descriptionArray.append(description)
}
if let thumbnails = items[i]["thumb_url"] as? NSDictionary
{
let thumbnail = thumbnails as! String
self.thumbnailArray.append(thumbnail)
}
}
}
self.resultsTableView.reloadData()
Create an OfferTableViewCell Class with a nameLabel:UILabel, descriptionLabel:UILabel, and thumbnailImage:UIImage. Finally in your cellForRowAtIndexPath.....
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("offer", forIndexPath: indexPath) as! OfferTableViewCell
cell.nameLabel.text = self.nameArray[indexPath.row]
cell.descriptionLabel.text = self.descriptionArray[indexPath.row]
let url = NSURL(string: self.thumbnailArray[indexPath.row])
let data = NSData(contentsOfURL: url!)
cell.thumbnailImage.image = UIImage(data: data!)
return cell
}

How do I push Json data to labels in a UITableView?

I've got 3 labels in a custom UITableview cell and I'm trying to pass in json data I've gotten from an api with Alamofire but I'm struggling to understand how to push the returned json into the tableview. Any help would be greatly appreciated.
Code below:
import UIKit
import Parse
import Alamofire
class LeagueTableController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "https://api.import.io/store/connector/88c66c----9b01-6bd2bb--d/_query?input=webpage/url:----") .responseJSON { response in // 1
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
return cell
}
}
Returned json like this:
{
connectorGuid = "88c66cb4-e64f-4316-9b01-6bd2bb2d762d";
connectorVersionGuid = "8aedfe43-948a-4559-b279-d3c3c28047a4";
cookies = (
);
offset = 0;
outputProperties = (
{
name = team;
type = URL;
},
{
name = played;
type = DOUBLE;
},
{
name = points;
type = DOUBLE;
}
);
pageUrl = "http://www.extratime.ie/leagues/2024/100/premier-division/";
results = (
{
played = 9;
"played/_source" = 9;
points = 22;
"points/_source" = 22;
team = "http://www.extratime.ie/squads/17/";
"team/_source" = "/squads/17/";
"team/_text" = Dundalk;
},
{
played = 9;
"played/_source" = 9;
points = 20;
"points/_source" = 20;
team = "http://www.extratime.ie/squads/7/";
"team/_source" = "/squads/7/";
"team/_text" = "Derry City";
},
{
played = 9;
"played/_source" = 9;
points = 17;
"points/_source" = 17;
team = "http://www.extratime.ie/squads/100504/";
"team/_source" = "/squads/100504/";
"team/_text" = "Galway United FC";
},
{
played = 9;
"played/_source" = 9;
points = 16;
"points/_source" = 16;
team = "http://www.extratime.ie/squads/29/";
"team/_source" = "/squads/29/";
"team/_text" = "St. Patrick's Ath";
},
{
played = 8;
"played/_source" = 8;
points = 15;
"points/_source" = 15;
team = "http://www.extratime.ie/squads/30/";
"team/_source" = "/squads/30/";
"team/_text" = "Cork City";
},
{
played = 8;
"played/_source" = 8;
points = 15;
"points/_source" = 15;
team = "http://www.extratime.ie/squads/3/";
"team/_source" = "/squads/3/";
"team/_text" = "Shamrock Rovers";
},
{
played = 9;
"played/_source" = 9;
points = 10;
"points/_source" = 10;
team = "http://www.extratime.ie/squads/13/";
"team/_source" = "/squads/13/";
"team/_text" = "Finn Harps";
},
{
played = 9;
"played/_source" = 9;
points = 10;
"points/_source" = 10;
team = "http://www.extratime.ie/squads/2/";
"team/_source" = "/squads/2/";
"team/_text" = Bohemians;
},
{
played = 9;
"played/_source" = 9;
points = 7;
"points/_source" = 7;
team = "http://www.extratime.ie/squads/8/";
"team/_source" = "/squads/8/";
"team/_text" = "Sligo Rovers";
},
{
played = 9;
"played/_source" = 9;
points = 7;
"points/_source" = 7;
team = "http://www.extratime.ie/squads/6/";
"team/_source" = "/squads/6/";
"team/_text" = "Bray Wanderers";
},
{
played = 9;
"played/_source" = 9;
points = 5;
"points/_source" = 5;
team = "http://www.extratime.ie/squads/109/";
"team/_source" = "/squads/109/";
"team/_text" = "Wexford Youths";
},
{
played = 9;
"played/_source" = 9;
points = 5;
"points/_source" = 5;
team = "http://www.extratime.ie/squads/15/";
"team/_source" = "/squads/15/";
"team/_text" = "Longford Town";
}
);
}
I'm trying to just push the "played", "points" and "team/_text" results out to each of the labels.
Since the question is very broad and doesn't specify what exactly is the problem here, The general steps are:
1) map your json to dictionary/nsdictionary. Suppose the JSON snippet you posted is a chunk of JSONArray in following format [{}], all you need to do is:
var arrayOfDictionaries:NSArray = NSJSONSerialization.JSONObjectWithData(yourData, options: nil, error: nil) as! NSArray
where yourData variable is data downloaded from network casted to NSData format
2) create outlets to these three labels in your custom tableViewCell
3) for each cell, set these labels inside
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
method as follows:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:YourCustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as YourCustomCell
cell.firstLabel.text = yourDictionary["played"]
cell.secondLabel.text = yourDictionary["points"]
cell.thirdLabel.text = yourDictionary["team"]
return cell
}
4) I suppose you will need more cells than just one, then store many dictionaries in array and access each element like this:
cell.firstLabel.text = arrayOfDictionaries[indexPath.row]["played"]
You'll need to create a subclass of UITableViewCell, say MyTableViewCell and add a property named JSON.
Now, since you're probably using Interface Builder to define your cell and its reuse identifier ("Cell"), set that cell's class to your newly created MyTableViewCell and connect the labels to some IBOutlets in your newly defined class.
Then, when you call 'dequeueReusableCellWithIdentifier', cast the cell to MyTableViewCell and set its JSON property to the value you want to have in the cell.
You'll probably want to react to the change, so add the didSet property observer.
var JSON:[String: AnyObject] = [String: AnyObject]() {
didSet {
print("populate your labels with your new data");
}
}
First, you should create a model that contain 3 properties that you want to save, like:
class Data {
var team = ""
var point = 0
var teamText = ""
init(fromJSON json: NSDictionary) {
team = json["team"] as! String
point = json["points"] as! Int
teamText = json["team/_text"] as! String
}
}
In your LeagueTableController, create an array to hold the data and show it to tableView:
var data = [Data]()
Config the tableView to show the data:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! YourCustomCell
let row = indexPath.row
cell.lblA.text = data[row].team
cell.lblB.text = "\(data[row].point)"
cell.lblC.text = data[row].teamText
return cell
}
Finally, parse your response json to our data array to display onto tableView
#IBOutlet weak var tableView: UITableView!
var data = [Data]()
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "https://api.import.io/store/connector/88c66c----9b01-6bd2bb--d/_query?input=webpage/url:----") .responseJSON { response in // 1
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
// parse JSON to get array of data
let array = JSON["results"] as! [NSDictionary]
// map an item to a data object, and add to our data array
for item in array {
self.data.append(Data(fromJSON: item))
}
// after mapping, reload the tableView
self.tableView.reloadData()
}
}
}
Hope this help!

Resources