Downloading calendar data in Objective-C - ios

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?

Related

Group element in NSMutableArray which contains object

I have an NSMutableArray that contains an object of a class model in each position like this.
The class model contains 2 types of information, which we will call id and name.
So, in every location of my NSMutableArray I have an object that contains 2 information.
Then, in the first position of my NSMutableArray I have
{
id = 1;
name = "Dan"; //this is the first object in NSMutableArray
}
In the second position of NSMutableArray, I have:
{
id = 1;
name = "Luca";
}
In the third position
{
id = 2;
name = "Tom";
}
and so on..
Ok, my goal is to make the union of identical IDs between the various objects within the SNMutableArray but it's too difficult!
For example, if I have:
{
id = 1;
name = "Tom";
}
{
id = 1;
name = "Luca";
}
{
id = 2;
name = "Steve";
}
{
id = 2;
name = "Jhon";
}
{
id = 3;
name = "Andrew";
}
The goal is:
{
id = 1;
name = "Tom";
name = "Luca";
}
{
id = 2;
name = "Steve";
name = "Jhon";
}
{
id = 3;
name = "Andrew";
}
Any ideas? would like to use this in the cellForRowAtIndexPath method and I tried to write this: (cm is my class model and myArray is the NSMutableArray which contains an object of cm class)
ClassModel *cm = [myArray objectAtIndex:indexPath.row];
NSMutableArray * resultArray = [NSMutableArray new];
NSArray * groups = [array valueForKeyPath:cm.ID];
for (NSString * groupId in groups)
{
     NSMutableDictionary * entry = [NSMutableDictionary new];
     [insert setObject: groupId forKey: # "groupId"];
     NSArray * groupNames = [array filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: # "groupId =% #", groupId]];
     for (int i = 0; i <groupNames.count; i ++)
     {
         NSString * name = [[groupNames objectAtIndex: i] objectForKey: # "name"];
         [entry setObject: name forKey: [NSS string stringWithFormat: # "name% d", i + 1]];
     }
     [resultArray addObject: entry];
}
NSLog (# "% #", resultArray);
But this does not work..maybe because each element in my array is an object?? .. Help!
You have the right basic idea, but you shouldn't try and do this in cellForRowAt. Rather, you need to create a new array that has the data in the required structure and use that array as the source for your tableview. You will also need to create a new class to put in the array; one that has an id and an NSMutableArray for the names (I won't show this but I will call it GroupClassModel)
Use something like:
NSMutableDictionary *groups = [NSMutableDictionary new]
for (ClassModel *cm in array) {
GroupClassModel *gcm = groups[cm.id];
if (gcm == nil) {
gcm = [GroupClassModel new];
gcm.id = cm.id
groups[cm.id] = gcm
}
[gcm.names addObject:cm.name];
}
NSArray *groupedName = [groups allValues];
// Finally, sort groupedName by id if that is required.

Parse YouTube JSON for UITableView

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
}

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.

Adding Multiple NSArrays to NSMutableDictionary with corresponding matching item in array order

I have two arrays say itemName and itemImages
NSArray *itemName = #[#"Blog", #"Missions", #"Subscriptions", #"Questions", #"Aide",#"Disconnect"];
NSArray *itemImages = #[#"ico-1",#"ico-2", #"ico-3", #"ico-4", #"ico-5", #"ico-6"];
I need to add them to a dictionary
NSMutableDictionary *menuItemNameImage = [[NSMutableDictionary alloc] init];
[menuItemNameImage setValue:itemName forKey:#"itemName"];
[menuItemNameImage setValue:itemImages forKey:#"itemImages"];
NSLog(#"%#", menuItemNameImage);
But this makes the following Dictionary
{
itemImages = (
"ico-1",
"ico-2",
"ico-3",
"ico-4",
"ico-5",
"ico-6"
);
itemName = (
Blog,
Missions,
Subscriptions,
Questions,
Aide,
Disconnect
);
}
What I rather want is some think like this :
{
{
itemImages = "icon-1",
itemName = Blog
},
{
itemImage = "icon-2",
itemName = "Missions"
}, ...
}
You cannot get that structure with a single NSDictionary - you need an NSArray of NSDictionary objects.
Here is how you can do it:
NSMutableArray *menuItemNameImage = [NSMutableArray array];
for (int i = 0 ; i != itemNames.count ; i++) {
[menuItemNameImage addObject: #{
#"itemName" : itemNames[i]
, #"itemImage" : itemImages[i]
}];
}
What you could use is a NSArray of NSDictionaries. Each dictionary would have two entries: an itemImage and itemName.
It would be something like this:
NSArray *itemName = #[#"Blog", #"Missions", #"Subscriptions", #"Questions", #"Aide",#"Disconnect"];
NSArray *itemImages = #[#"ico-1",#"ico-2", #"ico-3", #"ico-4", #"ico-5", #"ico-6"];
NSMutableArray *menuItemNameImage = [NSMutableArray new];
for (NSInteger i = 0; i < itemName.count; i++) {
NSMutableDictionary *itemNameImage = [NSMutableDictionary new];
itemNameImage[#"itemName"] = itemName[i];
//just a precaution if the array os images is smaller than the ones of names, to avoid unwanted crashes
if (i < itemImages.count) {
itemNameImage[#"itemImage"] = itemImages[i];
}
[menuItemNameImage addObject:itemNameImage];
}
NSLog(#"%#", menuItemNameImage);
The output, as you want:
(
{
itemImage = "ico-1";
itemName = Blog;
},
{
itemImage = "ico-2";
itemName = Missions;
},
{
itemImage = "ico-3";
itemName = Subscriptions;
},
{
itemImage = "ico-4";
itemName = Questions;
},
{
itemImage = "ico-5";
itemName = Aide;
},
{
itemImage = "ico-6";
itemName = Disconnect;
}
)
You can access the elements like this, for example:
NSString *firstItemName = menuItemNameImage[0][#"itemName"];
NSString *firstItemImage = menuItemNameImage[0][#"itemImage"];

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