Parse YouTube JSON for UITableView - ios

I am trying to have a UITableView that displays the title, thumbnail, viewcount, and duration of some youtube videos on a specific channel. The link is this
https://gdata.youtube.com/feeds/api/videos?q=remedyLIVE&max-results=5&v=2&alt=jsonc&orderby=published
And the JSON looks like this
{
apiVersion = "2.1";
data = {
items = (
{
accessControl = {
autoPlay = allowed;
comment = allowed;
commentVote = allowed;
embed = allowed;
list = allowed;
rate = allowed;
syndicate = allowed;
videoRespond = moderated;
};
aspectRatio = widescreen;
category = Music;
commentCount = 0;
content = {
1 = "rtsp://r3---sn-jc47eu7l.c.youtube.com/CiILENy73wIaGQkbMrdTdbNpexMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
5 = "https://www.youtube.com/v/e2mzdVO3Mhs?version=3&f=videos&app=youtube_gdata";
6 = "rtsp://r3---sn-jc47eu7l.c.youtube.com/CiILENy73wIaGQkbMrdTdbNpexMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
};
description = "In this episode of IchthusTV My Epic talks about seeking help within the church. -- Text 'Remedy' to 313131 if you need to chat. RemedyLIVE: We Chat, Listen, and Love www.remedyLIVE.com.";
duration = 109;
id = e2mzdVO3Mhs;
player = {
default = "https://www.youtube.com/watch?v=e2mzdVO3Mhs&feature=youtube_gdata_player";
mobile = "https://m.youtube.com/details?v=e2mzdVO3Mhs";
};
thumbnail = {
hqDefault = "https://i.ytimg.com/vi/e2mzdVO3Mhs/hqdefault.jpg";
sqDefault = "https://i.ytimg.com/vi/e2mzdVO3Mhs/default.jpg";
};
title = "My Epic - Help within the Church";
updated = "2014-11-11T20:00:03.000Z";
uploaded = "2014-11-11T20:00:03.000Z";
uploader = chatlistenlove;
},
{
accessControl = {
autoPlay = allowed;
comment = allowed;
commentVote = allowed;
embed = allowed;
list = allowed;
rate = allowed;
syndicate = allowed;
videoRespond = moderated;
};
aspectRatio = widescreen;
category = People;
commentCount = 0;
content = {
etc... I won't post the whole thing but you can see it on the link above! As this is my first time working with JSON I understand that I need to parse this to an array or dictionary but I am just a bit confused on what exactly the "objectforkey" methods look like once I have the data. None of the tutorials I see apply to what I am doing so specific help would be awesome! Here is my code so far
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.tableView registerNib:[UINib nibWithNibName:#"RemedyYouTubeTableViewCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"RemedyYouTubeTableViewCell"];
NSURL *youtubeURL = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos?q=remedyLIVE&max-results=5&v=2&alt=jsonc&orderby=published"];
NSData *data = [NSData dataWithContentsOfURL:youtubeURL];
if (data == nil)
{
NSLog(#"data is nil");
}
else
{
NSError *error;
titleArray = [[NSMutableArray alloc]init];
videoIDArray = [[NSMutableArray alloc]init];
thumbArray = [[NSMutableArray alloc]init];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", json);
for (NSDictionary *item in json)
{
NSDictionary* snippet = [item objectForKey:#"snippet"];
title = [snippet objectForKey:#"title"];
videoID = [[snippet objectForKey:#"resourceId"] objectForKey:#"videoId"];
thumbURL = [[[snippet objectForKey:#"thumbnails"] objectForKey:#"default"] objectForKey:#"url"];
[titleArray addObject:title];
[videoIDArray addObject:videoID];
[thumbArray addObject:thumbURL];
}
[self.tableView reloadData];
}
For example why is the word "snippet" chosen? I found this on another stack overflow post about this but I don't understand. Thanks in advance!

As mentioned in the comments, you can parse NSDictionary objects (translated by parsing JSON objects) using short hand notation. To get to the value you want, use something like this:
NSURL* playbackUrl = [NSURL urlWithString:yourDictionary[#"data"][#"items"][#"player"]["mobile"]];
To prevent crashes when the property doesn't exist, you'll want to use a try catch block:
#try {
NSURL* playbackUrl = [NSURL urlWithString:yourDictionary[#"data"][#"items"][#"player"]["mobile"]];
}
#catch (NSException *exception) {
// handle exception
}

Related

trouble with iOS9 search API NSUserActivity

When I watch videos about iOS9 search API WWDC2015,there is a demo like this:
var activity:NSUserActivity = NSUserActivity(activityType:"com.yummly.browseRecipe")
activity.title = "Baked Potato Chips"
activity.userInfo = ["id":"http://www.yummly.com/recipe/BPC-983195"]
activity.eligibleForSearch = true
activity.becomeCurrent()
I copy this code to my Xcode and run it, when I search by Spotlight, there is no results. What's wrong with it? Bug for iOS9?
For some reason, you must keep a reference to your NSUserActivity object after you call activity.becomeCurrent(). Like this (Swift):
activity.becomeCurrent()
self.lastActivity = activity
where "lastActivity" is a property of the class you are in.
I did like this, is in objective-C, but you can easily translate to swift
if ([CSSearchableItemAttributeSet class]) {
CSSearchableItemAttributeSet* attributes = [[CSSearchableItemAttributeSet alloc]initWithItemContentType:#"kUTTypePackage"];//Set you content type
attributes.title = model.name;
attributes.contentDescription = model.description;
attributes.identifier = model.fileURL.lastPathComponent;
UIImage* backImage = [UIImage imageWithData:model.imageData];
if (backImage == nil) {
attributes.thumbnailData = UIImageJPEGRepresentation([UIImage imageNamed:#"DefaultImage"], 0.5);
}else{
attributes.thumbnailData = model.imageData;
}
NSString* domainID = #"com.myapp.mycompany";
NSString* uniqueID = model.fileURL.lastPathComponent;
CSSearchableItem* item = [[CSSearchableItem alloc]initWithUniqueIdentifier:uniqueID //value passed from NSUserActivity inside .userInfo
domainIdentifier:domainID
attributeSet:attributes];
NSLog(#"Item Attributes:%#",item.attributeSet.identifier);
CSSearchableIndex* index = [CSSearchableIndex defaultSearchableIndex];
[index indexSearchableItems:#[item] completionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(#"Item \"%#\" indexed",model.name);
}else{
NSLog(#"Error, \"%#\" not indexed: %#, %#",model.name,error, error.userInfo);
}
}];
}else{
NSLog(#"iOS < 9");
}
You need to attach the NSUserActivity to the controller like below.
controller.userActivity = activity

Downloading calendar data in Objective-C

I am trying to download google calendar data.
I am following a tutorial this link according to which implementing some of the GoogleOAuth delegate methods will let me get my desired data.
First I converted the response JSON data into an NSDictionary object and after that, I, NSLog this dictionary, to see the way the returned data is formed which is as shown below.
calendarInfoDict is {
etag = "\"1436255371893000\"";
items = (
{
accessRole = owner;
backgroundColor = "#9a9cff";
colorId = 17;
defaultReminders = (
{
method = popup;
minutes = 30;
}
);
etag = "\"1436255371893000\"";
foregroundColor = "#000000";
id = "sabiranthapa#gmail.com";
kind = "calendar#calendarListEntry";
notificationSettings = {
notifications = (
{
method = email;
type = eventCreation;
},
{
method = email;
type = eventChange;
},
{
method = email;
type = eventCancellation;
},
{
method = email;
type = eventResponse;
}
);
};
primary = 1;
selected = 1;
summary = "sabiranthapa#gmail.com";
timeZone = "Asia/Calcutta";
},
{
accessRole = reader;
backgroundColor = "#92e1c0";
colorId = 13;
defaultReminders = (
);
description = "Displays birthdays of people in Google Contacts and optionally \"Your Circles\" from Google+. Also displays anniversary and other event dates from Google Contacts, if applicable.";
etag = "\"1436255358367000\"";
foregroundColor = "#000000";
id = "#contacts#group.v.calendar.google.com";
kind = "calendar#calendarListEntry";
summary = Birthdays;
timeZone = "Asia/Calcutta";
}
);
kind = "calendar#calendarList";
nextSyncToken = 00001436255371893000;
}
According to tutorial there is a block containing a bunch of information regarding every calendar I have created in Google Calendars inside curly bracket. But I am not getting any events that I have saved which can be seen in Google Calendar after signing in gmail but not in my apps where I need to work with it.
My code is
-(void)responseFromServiceWasReceived:(NSString *)responseJSONAsString andResponseJSONAsData:(NSData *)responseJSONAsData{
NSError *error;
if ([responseJSONAsString rangeOfString:#"calendarList"].location != NSNotFound) {
NSDictionary *calendarInfoDict = [NSJSONSerialization JSONObjectWithData:responseJSONAsData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"calendarInfoDict is %#", calendarInfoDict);
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
else{
NSArray *calendarsInfo = [calendarInfoDict objectForKey:#"items"];
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
for (int i=0; i<[calendarsInfo count]; i++) {
NSDictionary *currentCalDict = [calendarsInfo objectAtIndex:i];
NSArray *values = [NSArray arrayWithObjects:[currentCalDict objectForKey:#"id"],
[currentCalDict objectForKey:#"summary"],
nil]; NSArray *keys = [NSArray arrayWithObjects:#"id", #"summary", nil];
[_arrGoogleCalendars addObject:
[[NSMutableDictionary alloc] initWithObjects:values forKeys:keys]];
}
_dictCurrentCalendar = [[NSDictionary alloc] initWithDictionary:[_arrGoogleCalendars objectAtIndex:0]];
[_barItemPost setEnabled:YES];
[_barItemRevokeAccess setEnabled:YES];
[self showOrHideActivityIndicatorView];
But I always end up with condition
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
without able to access my events.
How can I download (or access) my Events from google calendar?

how to make a new NSDictionary from a NSDictionary where key = x

i have a app that gets some json data from a mysql server via a web api like this:
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"streamGames", #"command", nil] onCompletion:^(NSDictionary *json) {
//got stream
[[API sharedInstance] setGames:[json objectForKey:#"result"]];
this gives me :
{
awayScor = 3;
data = "2014-04-11";
gameType = 1;
homeScor = 2;
homeTeam = "Herning Blue Fox";
time = "21:00";
},
{
awayScor = 1;
data = "2014-04-08";
gameType = 2;
homeScor = 2;
homeTeam = "SønderjyskE";
time = "19:00";
},
now what i want to do i make a new NSDictionary where i only add data where lets say gameType = 1 so i have a new NSDictionary for etch gameType.
If I've understood the question correctly!
NSArray *games; // Get this from somewhere
NSMutableDictionary *gameTypes = [NSMutableDictionary dictionary];
for (NSDictionary *game in games) {
NSNumber *gameType = game[#"gameType"];
NSMutableArray *gamesForType = gameTypes[gameType];
if (!gamesForType) {
gamesForType = [NSMutableArray array];
gameTypes[gameType] = gamesForType;
}
[gamesForType addObject:game];
}
Now gameTypes will be a dictionary of game types to an array games of that type.

IOS JSON Parsing Nested Data

Well I guess its an easy question (because I am only learning IOS recently).
Most of the tutorials that I have seen show simple JSON key value examples.
However I am looking a JSON structure which has the following format:
So I have lets say a JSON page that displays something like:
loans: (
{
activity = "Personal Products Sales";
"basket_amount" = 0;
"bonus_credit_eligibility" = 1;
"borrower_count" = 1;
description = {
languages = (
en
);
};
"funded_amount" = 0;
id = 623727;
image = {
id = 1457061;
"template_id" = 1;
};
"loan_amount" = 475;
location = {
country = Philippines;
"country_code" = PH;
geo = {
level = country;
pairs = "13 122";
type = point;
};
town = "Maasin City, Leyte";
};
name = Zita;
"partner_id" = 145;
"planned_expiration_date" = "2013-11-28T21:00:02Z";
"posted_date" = "2013-10-29T21:00:02Z";
sector = Retail;
status = fundraising;
use = "to buy additional stocks of soap, toothpaste, dish washing products, etc.";
},
So for example if I want to extract the name I understand the key pair ideas so I just do something like:
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString *name = [loan objectForKey:#"name"];
And then *name should evaluate to : Zita.
But my question is ....
1) What wizardry do I need to do in order to get access data deep inside the structure like "level = country;" (the level is located inside "geo" which is located inside "location")
Can someone explain how to do this ?
Exactly the same way as you're doing right now :)
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSDictionary* location = [loan objectForKey:#"location"];
NSDictionary* geo = [locationobjectForKey:#"geo"];
NSString* level = [geo objectforKey:#"country"];
or shorter:
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString* level = loan[#"location"][#"geo"][#"level"];

Accessing the xml values from NSDictionary

I am using this xmlreader. Here is my code
NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:&error1];
NSLog(#"XMLData: %#",xmlDict);
I can save and log the data and it looks like this.
response = {
Gpn0 = {
text = 10000;
};
Gsn0 = {
text = 4;
};
btn0 = {
text = up;
};
};
}
But how can I access a single element from this dictionary?
NSDictionary *gpn0 = response[#"Gpn0"];
NSNumber *gpn0_text = gpno[#"text"]; // note this is a numeric value
NSDictionary *btn0 = response[#"btn0"];
NSString *btn0_text = gpno[#"text"]; // note this is a string value
so on and so forth

Resources