xcode JSON trouble - xcode

I have a problem with this code right here:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* announcements = [json objectForKey:#"clients"];
NSLog(#"laag 1: %#", announcements);
NSDictionary* announcement = [announcements objectAtIndex:0];
NSNumber *status = [announcement objectForKey:#"status"];
humanReadble.text = [NSString stringWithFormat:#"%#", status];
}
I'm trying to fetch JSON data from this URL. I know the fetching works, the NSLog displays it fine, but the problem begins at the NSDictionary. I did some tests with breakpoints and found that the error was there. This is a overview of my log:
2012-03-20 23:15:13.210 Json test 2[13248:f803] laag 1: {
client = (
{
companyname = xxx;
datecreated = "2012-03-11";
email = "xxxx";
firstname = xxx;
groupid = 0;
id = 3;
lastname = O;
status = Active;
},
{
companyname = "xxx";
datecreated = "2012-03-02";
email = "xxx";
firstname = xxx;
groupid = 0;
id = 1;
lastname = "xxx";
status = Active;
},
{
companyname = "";
datecreated = "2012-03-08";
email = "xxx";
firstname = xxx;
groupid = 0;
id = 2;
lastname = xxx;
status = Active;
},
{
companyname = xxx;
datecreated = "2012-03-13";
email = "xxx";
firstname = xxx;
groupid = 0;
id = 4;
lastname = "xxx";
status = Active;
}
);
}
2012-03-20 23:15:13.212 Json test 2[13248:f803] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6821f30
2012-03-20 23:15:13.213 Json test 2[13248:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6821f30'
*** First throw call stack:
(0x13c7022 0x1558cd6 0x13c8cbd 0x132ded0 0x132dcb2 0x21a2 0x13c8e42 0x9379df 0x139b94f 0x12feb43 0x12fe424 0x12fdd84 0x12fdc9b 0x12b07d8 0x12b088a 0x11626 0x1c3d 0x1ba5)
terminate called throwing an exception(lldb)
Can someone please help me out?
I use sdk 5.1, xcode 4.3 on lion 10.7.3

The object returned by [json objectForKey:#"clients"] in your code is actually a dictionary, not an array. First you need to extract the "client" object (which is the array you want) from that dictionary. You can do it like this:
NSDictionary *clients = [json objectForKey:#"clients"];
NSArray *announcements = [clients objectForKey:#"client"];
NSDictionary* announcement = [announcements objectAtIndex:0];

Related

Checking if a value exists in a NSDictionary for local notifications

So im using local notifications to send a daily notification to the user, once the notifcation is added i add an id in the userInfo - NSDictionary. The user can remove the medication at any time which will cancel the notification which is why i add the id into the NSDictionary.
var notification = new UILocalNotification();
Random rnd = new Random();
string stringid = rnd.Next(1, 1000000000).ToString();
notification.AlertBody = usermedid + "Please take " + dosage + " of " + medname;
stringid = notification.AlertBody;
App.BadgeCount = App.BadgeCount + 1;
notification.ApplicationIconBadgeNumber = App.BadgeCount;
notification.FireDate = NSDate.FromTimeIntervalSinceNow(60);
notification.RepeatInterval = NSCalendarUnit.Minute;
var userInfo = NSDictionary.FromObjectAndKey(new NSString("UsermeddosageID"),new NSString(usermeddosagetimeid));
notification.UserInfo = userInfo;
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
The code is inserting the id into the NSDictionary but for some reason it wont read it in my IF Statement. Can anybody explain why my code isnt working ?? Any help appreciated..
var array = UIApplication.SharedApplication.ScheduledLocalNotifications;
foreach (var item in array)
{
var userinfo = item.UserInfo;
if (!userinfo.ContainsKey(new NSString(usermeddosagetimeid)))
{
UIApplication.SharedApplication.CancelLocalNotification(item);
}
}
If I understand right, if you want to cancel the notification which contains the key usermeddosagetimeid, the if Statement should be:
if (userinfo.ContainsKey(new NSString(usermeddosagetimeid)))
{
UIApplication.SharedApplication.CancelLocalNotification(item);
}
Instead of !userinfo.ContainsKey(new NSString(usermeddosagetimeid))
BTW, scheduledlocalnotifications is Deprecated since iOS 10, you can use the UNUserNotificationCenter class to schedule local notifications instead.

Receive a notification key from ios

I have the following command where I get my notification in ios, I want to get my key more I'm not getting it, what I tried was
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
Messaging.SharedInstance.AppDidReceiveMessage(userInfo);
NSString[] keys = { new NSString("Event_type") };
NSObject[] values = { new NSString("Recieve_Notification") };
var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);
Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);
System.Diagnostics.Debug.WriteLine(userInfo);
// var aps_d = userInfo["aps"] as NSDictionary;
//var alert_d = aps_d["alert"] as NSDictionary;
//var body = alert_d["keys"] as NSString;
}
System.Diagnostics.Debug.WriteLine
receive this
[0:] {
aps = {
alert = {
body = "teste";
title = "teste";
};
};
"gcm.message_id" = "0:1505400569099941%712ac0f8712a1234";
"gcm.n.e" = 1;
"google.c.a.c_id" = 5974019197827881234;
"google.c.a.c_l" = "teste";
"google.c.a.e" = 1;
"google.c.a.ts" = 1505400123;
"google.c.a.udt" = 0;
keys = 152113;
}
keys is a top level and last entry in the dictionary, so you can directly access it via userInfo["keys"], i.e:
var keys = userInfo["keys"] as NSString;

Xcode Debbugger in Swift : show managedObject

I was wondering if there is a way to display more readable description of managed object in XCode 6 when developping in Swift.
Cause now it displays :
//Printing description of station:
(targetName.BDD_Station) station = 0x00000001700dfdb0 {
targetName.BDD_Station = {
CoreData.NSManagedObject = {
ObjectiveC.NSObject = {}
}
}
Before it was nicer :)
<BDD_Station: 0x1702d6180> (entity: BDD_Station; id: 0xd0000000bb7c0008 <x-coredata://DFA941DB-A7E7-406F-B415-B628AA4D8FF1/BDD_Station/p11999> ; data: {
address = "254, Alexander Platz ";
address2 = "";
area = 72;
"brand_code" = TAC;
"brand_id" = 420;
"brand_name" = "HARIBO";
cheapest = nil;
city = PARIS;
code = NF000337;
"corporate_name" = nil;
country = FRANCE;
department = nil;
distance = 0;
email = "";
fax = nil;
ident = 827752;
latitude = "48.1278";
longitude = "-2.64937";
"map_id" = 744;
name = "my beautiful name";
"original_name" = nil;
phone = 0143543211;
toDelete = 0;
zip = 72000;
})
I tried to override var description, but it does'nt get called when I click "show description" in debugger.
Thanks for your help.

How to get the parse values?

i am writing the code below manner.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions error:&error];
NSLog(#"%#",json);
The printed dictionary is
(
{
Contents = (
{
Id = 2;
LastUpdated = "/Date(1338048712847+0000)/";
Title = "Webinar: HP & MS solutions for Mid-Market";
Url = "http://infra2apps.blob.core.windows.net/content/VMMM019-HP-MS_MidMarket.wmv";
},
{
Id = 1;
LastUpdated = "/Date(1338048712773+0000)/";
Title = "Webinar: Private Cloud with HP & MS";
Url = "http://infra2apps.blob.core.windows.net/content/VMPC012-HPMS_PrivateCloud.wmv";
}
);
Id = 1;
ImageUrl = "http://infra2apps.blob.core.windows.net/eventapp/black-microsoft-logo.jpg";
Name = "Unified Communications & Collaborations";
Sessions = (
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275822000000+0000)/";
FriendlyName = TB3257;
Id = 1;
Location = "Building N-4105";
Speakers = (
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275818400000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync";
},
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275825600000+0000)/";
FriendlyName = TB3258;
Id = 2;
Location = "Building N-4105";
Speakers = (
{
Company = HP;
Email = "janedoe#hp.com";
Name = "Jane Doe";
Title = "Vice President";
},
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275822000000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync - Part 2";
}
);
},
....etc
And then store the content values into another dictionary after that i store into an array.
the below code is to store the array id
NSDictionary *boothmenucontents = [json valueForKey: #"Contents"];
NSMutableArray *dictResponseboothmenucontentsArray = [[NSMutableArray alloc] initWithObjects: boothmenucontents,nil];
for(int i = 0; i<[dictResponseboothmenucontentsArray count]; i++)
{
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
NSLog(#"id array is %#",IdArrayboothmenucontentes);
for(int k=0;k<[IdArrayboothmenucontentes count];k++)
{
NSString * strcontentId= [NSString stringWithFormat:#"%#",[IdArrayboothmenucontentes objectAtIndex:k]];
NSLog(#"strcontentId%#",strcontentId);
label.text=strcontentId;
[boothmenuidarrayvalues addObject:strcontentId];
NSLog(#"%#",boothmenuidarrayvalues);
}
}
finally i print the boothmenuidarrayvalues
it print like this
"(\n 2,\n 1\n)",
"(\n 4,\n 3\n)",
"(\n 6,\n 5\n)",
"(\n 8,\n 7\n)",
"(\n 10,\n 9\n)",
"(\n 12,\n 11\n)"
but i want to print content id only once but it print in a row in two times.
May be i follow a wrong method please tell me how to give own root for that response.
Please help me.......
Perhaps It will help you.
NSMutableArray *contenstsArray = [contentsDictionary ValueForKey:#"Contents"]; //Suppose you already brought all the json data into contentsDictionary
NSMutableArray *idArray = [[NSMutableArray alloc] init];
for(NSMutableDictionary *idDic in contenstsArray) {
NSString *idString = [idDic valueForKey:#"Id"];
[idArray addObject:];
}
This line looks wrong:
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
I'm not sure what you are expecting it to do, but what it looks like it does is grab the ith object in the dictResponseboothmenucontentsArray, which is a dictionary and then gets the object in that dictionary with the key "Id", which is an number, so IdArrayboothmenucontentes now contains an NSNumber, not an array.

Xcode how to parse Json Objects

I manage to get Json for my server and parse in Xcode , I can then convert Json to a object and loaded my uitableview, the problems is my Json have 7 objects ..
you can see the full Json here
2012-05-05 10:45:02.727 passingdata[63856:fb03] array : {
posts = {
Friday = (
{
GymClass = {
"CLASS-TYPE2" = "";
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Friday;
TIME = "13:00 - 14:30";
};
}
);
Monday = (
{
GymClass = {
"CLASS-TYPE2" = "Fighters Training";
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Muay Thai ";
"DAY_OF_WEEK" = Monday;
TIME = "09:30 - 11:00";
};
}, ......
with this code I can get friday's "Friday" and display the GymClass info "GymClass" on my table
- (void)fetchedData:(NSData *)responseData { //parse out the json data
searchResults2 = [NSMutableArray arrayWithCapacity:10];
NSError* error;
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
if (array == nil) {
NSLog(#"Expected 'posts' array");
return;
}
for (NSDictionary *resultDict in array)
{
SearchResult *searchResult3;
searchResult3 = [self parseTrack:resultDict];
if (searchResult3 != nil) {
[searchResults2 addObject:searchResult3];
}
}
[self.tableView reloadData];
}
- (SearchResult *)parseTrack:(NSDictionary *)dictionary
{
SearchResult *searchResult1 = [[SearchResult alloc] init];
searchResult1.classType= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_TYPE"];
searchResult1.classLevel= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_LEVEL"];
NSLog(#"parse track = %#", searchResult1);
return searchResult1;
}
I can get the elements for one day but how do I get the Elements for every day (Mon,Tue...Sun)so i can display on my table by sections?
thanks for your help..
Well in your code, you already are doing that:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
Wen can start from there to retrieve only the object posts:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *posts = [dictionary objectForKey:#"posts"];
//Iterate over posts
for (NSArray *aDay in posts){
//Do something
NSLog(#"Array: %#", aDay);
}
Here, i am using Fast Enumeration to iterate over the dictionary, you should check this here.

Resources