issue while printing instgram post response on label - ios

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

Related

How to show image from json in table view

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

How to print a list of video titles from a YouTube channel with Swift 3?

I want to print every "title" in "items", "snippet", but my for-loop isn't executing for some reason. If someone can help me, thanks in advance.
code:
let url = URL(string: "https://www.googleapis.com/youtube/v3/search?key=\(key)&channelId=\(channelID)&part=snippet,id&order=date&maxResults=20")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("ERROR")
} else {
if let content = data {
do {
let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
for _ in json as! [String: AnyObject] {
if let items = json["items"] as? NSDictionary {
print(items)
if let snippet = items["snippet"] as? NSDictionary {
print(snippet)
if let title = snippet["title"] as? NSDictionary {
print(title)
}
}
}
}
} catch {
print("ERROR")
}
}
}
}
task.resume()
the JSON -I made it a lot shorter because there is a limit- I receive from Google is:
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/VCbtvQebUdRw3e7_zJbfxm0jID4\"";
items = (
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/LEyFeYOSX6YKSwwyN5aSWbiKNcA\"";
id = {
kind = "youtube#video";
videoId = YT6G4Cg60xE;
};
kind = "youtube#searchResult";
snippet = {
channelId = UCuP2vJ6kRutQBfRmdcI92mA;
channelTitle = "Lets Build That App";
description = "Facial detection is a new piece technology that's getting better and better over time. However, upon trying out Apple's new Vision API we can see that there is still ...";
liveBroadcastContent = none;
publishedAt = "2017-07-12T15:00:06.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/YT6G4Cg60xE/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/YT6G4Cg60xE/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/YT6G4Cg60xE/mqdefault.jpg";
width = 320;
};
};
title = "Is Apple's Vision Racially Biased?";
};
},
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/zooINPhLwlR1Dm6MxGKbMzeFtMY\"";
id = {
kind = "youtube#video";
videoId = hPQIRIl977I;
};
kind = "youtube#searchResult";
snippet = {
channelId = UCuP2vJ6kRutQBfRmdcI92mA;
channelTitle = "Lets Build That App";
description = "I often get questions about how I got started in programming and what kind of portfolio projects to include in a resume. Well, let me show you a video I uploaded ...";
liveBroadcastContent = none;
publishedAt = "2017-07-10T15:00:06.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/hPQIRIl977I/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/hPQIRIl977I/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/hPQIRIl977I/mqdefault.jpg";
width = 320;
};
};
title = "My First Portfolio Project when Applying for Software Jobs";
};
},
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/n313rK9YZDxF118LMEo6i4X_Oz4\"";
id = {
kind = "youtube#video";
videoId = ZVCMV4a3KRw;
};
kind = "youtube#searchResult";
snippet = {
channelId = UCuP2vJ6kRutQBfRmdcI92mA;
channelTitle = "Lets Build That App";
description = "Often times I take questions from you guys that watch the channel and today I wanted to flip the script and get some input. I'm genuinely curious about what you ...";
liveBroadcastContent = none;
publishedAt = "2017-07-09T19:42:59.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/ZVCMV4a3KRw/mqdefault.jpg";
width = 320;
};
};
title = "Why do you guys watch the live stream?";
};
},
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/Q38Ub7-kDjTpoE407EG2kKc50xo\"";
id = {
kind = "youtube#video";
videoId = d0U5j89M6aI;
};
kind = "youtube#searchResult";
snippet = {
channelId = UCuP2vJ6kRutQBfRmdcI92mA;
channelTitle = "Lets Build That App";
description = "Face detection has been available through 3rd party APIs for a while now. Finally we have native support for this feature using Vision APIs with Xcode 9 and ...";
liveBroadcastContent = none;
publishedAt = "2017-07-08T15:00:06.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/d0U5j89M6aI/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/d0U5j89M6aI/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/d0U5j89M6aI/mqdefault.jpg";
width = 320;
};
};
title = "Super Impressive and Easy Face Detection using Vision API in Swift 4";
};
},
{
etag = "\"m2yskBQFythfE4irbTIeOgYYfBU/ZADZ11_Ev4ItFjXj09gohLZCoMU\"";
id = {
kind = "youtube#video";
videoId = 1RMkGkL9L3U;
};
kind = "youtube#searchResult";
snippet = {
channelId = UCuP2vJ6kRutQBfRmdcI92mA;
channelTitle = "Lets Build That App";
description = "Today we answer a question on how helpful Udemy, Udacity, or formal education from colleges are when it comes to learning new skills required for contracting ...";
liveBroadcastContent = none;
publishedAt = "2017-07-05T15:00:01.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/1RMkGkL9L3U/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/1RMkGkL9L3U/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/1RMkGkL9L3U/mqdefault.jpg";
width = 320;
};
};
title = "How I Learn New Skills for the Job - Udemy, Udacity, College, Google?";
};
},
First of all don't use NSDictioanry and NSArray in Swift instead of that use Swift native type Dictionary([:]) and Array([]) because with this compiler will easily understand what type of value object having. Also in Swift there is no need to specify mutableContainers option, to get mutable object you need to simply declare it with var.
Now in your JSON response items is Array of Dictionary not directly Dictionary and title is inside the snippet dictionary of each dictionary of this items array, so you need to loop through the items array instead of loop through the JSON.
if let content = data {
if let json = (try? JSONSerialization.jsonObject(with: content, options: [])) as? [String:Any],
let items = json["items"] as? [[String:Any]] {
for item in items {
if let snippet = item["snippet"] as? [String:Any],
let title = snippet["title"] as? String {
print(title)
}
}
}
}

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

Getting sorted data by the value of child of randomly generated key

-Chat
-Messages
-RandomID
-Timestamp <---- Sorting by this value
I'm having a trouble getting the sorted data by the value of timestamp.
class GetChat {
fileprivate var ref = FIRDatabaseReference.init()
var tripArray = NSDictionary()
func getMessage(tripID : String) {
let userID = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
//CHECK HERE FOR QUERY
let chatRef = ref.child("Trip").child("Users").child(userID!).child("TripList").child(tripID).child("messages").queryOrdered(byChild: "timestamp")
chatRef.observe(FIRDataEventType.value, with: { (snapshot) in
let chatData = snapshot.value as! NSDictionary
self.tripArray = chatData
print(chatData)
})
}
}
This is the print out
{
"-KSJwiXGN8_jfuxz3XLU" = {
arrivaltime = "2:19 AM";
classtype = BUSINESS;
depaturetime = "4:19 AM";
duration = "-2:0";
endpoint = NPD;
flightname = "AIR MANDALAY";
message = "Flight Info";
price = 216;
processtype = Flight;
senderid = SFwmYDYRV3a6FJSSov6wsoLY0yv2;
startdate = "Thu,24/09";
startpoint = YGN;
status = 2;
stop = 2;
timestamp = "1481528287.151";
type = form;
};
"-KSKNuQnEA__57zSb0Nf" = {
address = hvb;
checkin = "Sun,27/09";
checkout = "Wed,30/09";
hotelname = mandalay;
message = "Hotel Info";
price = "41.6";
processtype = Hotel;
rating = 3;
roomtype = deluxe;
senderid = SFwmYDYRV3a6FJSSov6wsoLY0yv2;
status = 0;
timestamp = "1481528287.153";
totalnight = 4;
totalprice = 2246;
type = form;
};
"-KYlxp2OhxNYs_3-5gfr" = {
message = "hello baby";
senderid = CLZV060eKBOveRIm2zcpd8PfT5w2;
timestamp = "1481528287.152";
type = text;
};
}
As you can see.
The print out is not sorted in order from low to high on the value of timestamp.

How to check value exists in array of dictionary as value?

{
QueueId = 27;
SongId = 38;
artWorkURL = "<null>";
duration = 58258;
"stream_url" = "https://api.soundcloud.com/tracks/233301835/stream";
title = Magenta;
trackID = 233301835;
userAvatar = "https://i1.sndcdn.com/avatars-000188204071-llusgk-large.jpg";
userName = Agiv;
},
{
QueueId = 27;
SongId = 39;
artWorkURL = "<null>";
duration = 79000;
"stream_url" = "https://api.soundcloud.com/tracks/233301833/stream";
title = Nino;
trackID = 233301833;
userAvatar = "https://i1.sndcdn.com/avatars-000157591669-eva3mg-large.jpg";
userName = "SWR Umwelt und Ern\U00e4hrung";
}
My array of dictionary format is as above and multiple tracks i want to check 27 is already there or not ?
You can do this with the filter function
let queueID27Exists = !array.filter({$0["QueueId"] as? Int == 27}).isEmpty
This answer is for your previous JSON object!
if let results : NSDictionary = post.objectForKey("data") as? NSDictionary {
let array:NSArray = (results.valueForKey("track") as! NSArray)
if "25" == array[0].valueForKey("trackID") as? String {
NSLog("YES")
} else {
NSLog("NO")
}
}
var found = false
for (_, data) in post {
let track = data["track"]
if track["trackID"] == "25" {
found = true
}

Resources