Remove repetitive keys value from NSArray - ios

{
ImageName = "http://192.168.1.8:9701/190214/190214_image2_08_13_2016_11_55_44.jpg";
ImagePath = "<null>";
ImageTypeId = 2;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image3_08_13_2016_11_55_45.jpg";
ImagePath = "<null>";
ImageTypeId = 3;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image4_08_13_2016_11_55_48.jpg";
ImagePath = "<null>";
ImageTypeId = 4;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image5_08_13_2016_11_55_51.jpg";
ImagePath = "<null>";
ImageTypeId = 5;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image6_08_13_2016_11_55_53.jpg";
ImagePath = "<null>";
ImageTypeId = 6;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image0_08_13_2016_06_15_21.jpg";
ImagePath = "<null>";
ImageTypeId = 0;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image1_08_13_2016_07_19_57.jpg";
ImagePath = "<null>";
ImageTypeId = 1;
},
{
ImageName = "http://192.168.1.8:9701/190214/190214_image1_08_13_2016_07_19_57.jpg";
ImagePath = "<null>";
ImageTypeId = 1;
}
)
I want to remove all the objects whose key is repetitive
For Ex. ImageTypeId = 1; object is two time so want to remove 1 object and only one object with ImageTypeId = 1;

Create a dictionary to hold the values:
var dict = [NSObject: AnyObject]()
Add each item to the dictionary using the typeid as the key:
for item in arr {
guard let typeid = item["ImageTypeId"] as? NSObject else { continue }
dict[typeid] = item
}
Create an array with the dictionary values:
let newarray = Array(dict.values)

Related

How to access a nested dictionaries from API

Let's say that I want to access an nest dictionary response from API like this format:
(
{
"active_upcoming_bookings" = (
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-23T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 75;
"desk_name" = D2;
"desk_type" = Standing;
id = 299;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 11;
wing = Right;
},
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-23T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 74;
"desk_name" = D3;
"desk_type" = Standing;
id = 300;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 12;
wing = Right;
},
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-01T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 76;
"desk_name" = D1;
"desk_type" = Standing;
id = 298;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 16;
wing = Right;
}
);
project = {
"created_at" = "2017-05-31T16:29:06.012+08:00";
"created_by_id" = 1;
"end_date" = "2018-03-23T23:59:59.999+08:00";
id = 8;
name = "expo 2017";
"start_date" = "2018-03-01T00:00:00.000+08:00";
"updated_at" = "2017-05-31T16:29:06.012+08:00";
};
}
)
My code for access the nested dictionary:
let response = responseJSON as! [String: [String: Any]]]()
let projectId = response["project"]?["id"] as Int
let projectName = response["project"]?["name"] as String
but it pops up subscript error in compiler.
What kind of data model should I use for access this?
Your JSON response is Array not Dictionary and active_upcoming_bookings array and project dictionary is within the first dictionary of your response Array.
if let response = responseJSON as? [[String:Any]], let dictionary = response.first,
let projectDic = dictionary["project"] as? [String:Any] {
//Now subscript with projectDic to access id and name
let projectId = projectDic["id"] as? Int
let projectName = projectDic["name"] as? String
}
Try this
let mainDict = arrResponse[0] as! [String : Any]
let projectDict = mainDict["project"] as! [String : Any]
let strProjectID = projectDict["id"] as! Int

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.

Swift 3: Accessing nested dictionary from returns nil?

I'm having a problem trying to access a nested Dictionary, which seems to return nil.
Here's the output my info of type Dictionary<String, Any>:
info = ["list_order": 1, "name": Some Text, "id": 1, "menu_items": {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}]
The output of info["menu_items"]:
info["menu_items"] = {
1 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "2.00";
id = 1;
};
2 = {
"food_name" = "String";
"food_picture" = "link";
"food_price" = "5.00";
id = 2;
};
}
However, the following assigning produces a nil in test:
let test = info["menu_items"] as? Dictionary<Int, Any>
Is there something not obvious or am I not understanding basic fundamentals?
If your key is not Int type then most probably it is of String type, try once using [String: Any].
if let menuItems = info["menu_items"] as? [String: Any] {
print(menuItems)
}

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