Getting data from NSDictinionary [closed] - ios

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to get the "firstName" , "lastName" , "gender", "homeCity" and "email" from a NSDictionary
but It doesn't work...I have tried the following code:
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [userInfo objectForKey:#"firstName"]);
NSLog(#"lastName: %#", [userInfo objectForKey:#"lastName"]);
NSLog(#"gender: %#", [userInfo objectForKey:#"gender"]);
NSLog(#"homeCity: %#", [userInfo objectForKey:#"homeCity"]);
NSLog(#"email: %#", [userInfo objectForKey:#"email"]);
here is my dictionary value...
userInfo: {
userDictionary = {
meta = {
code = 200;
errorDetail = "Please provide an API version to avoid future errors.See http://bit.ly/vywCav";
errorType = deprecated;
};
notifications = (
{
item = {
unreadCount = 0;
};
type = notificationTray;
}
);
response = {
user = {
badges = {
count = 0;
items = (
);
};
bio = "";
checkinPings = off;
checkins = {
count = 0;
};
contact = {
email = "email#email.com";
};
firstName = Name;
following = {
count = 0;
};
friends = {
count = 0;
groups = (
{
count = 0;
items = (
);
name = "Amigos em comum";
type = friends;
},
{
count = 0;
items = (
);
name = "Outros amigos";
type = others;
}
);
};
gender = male;
homeCity = "";
id = 3233312;
lastName = lastName;
lists = {
groups = (
{
count = 1;
items = (
);
type = created;
}
);
};
mayorships = {
count = 0;
items = (
);
};
photo = "https://foursquare.com/img/blank_boy.png";
photos = {
count = 0;
items = (
);
};
pings = 0;
referralId = "u-sdsad";
relationship = self;
requests = {
count = 0;
};
scores = {
checkinsCount = 0;
goal = 50;
max = 0;
recent = 0;
};
tips = {
count = 0;
};
todos = {
count = 0;
};
type = user;
};
};
};
}

Use [userInfo objectForKey:#"userDictionary"] objectForKey:#"response"] objectForKey:#"user"] objectForKey:#"homeCity"].

This is where key-value coding (KVC) comes in handy. You can do (note use of valueForKey::
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [userInfo valueForKey:#"response.user.firstName"]);
NSLog(#"lastName: %#", [userInfo valueForKey:#"response.user.lastName"]);
NSLog(#"gender: %#", [userInfo valueForKey:#"response.user.gender"]);
NSLog(#"homeCity: %#", [userInfo valueForKey:#"response.user.homeCity"]);
NSLog(#"email: %#", [userInfo valueForKey:#"response.user.email"]);
But this isn't very efficient since you keep digging deep into the same dictionary. It would be better to do this:
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSDictionary *user = [userInfo valueForKey:#"response.user"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [user objectForKey:#"firstName"]);
NSLog(#"lastName: %#", [user objectForKey:#"lastName"]);
NSLog(#"gender: %#", [user objectForKey:#"gender"]);
NSLog(#"homeCity: %#", [user objectForKey:#"homeCity"]);
NSLog(#"email: %#", [user objectForKey:#"email"]);

It doesn't work because your userInfo doesn't have such keys.
userInfo has userDictionary, which has meta, notifications and response.
response has user, and user has firstName, lastName etc.

Your top leve is userInfo, but there are "objects" within that as well. You will have to traverse those to get to first name. Something like this will work:
NSLog(#"first name = %#", userInfo[#"userInfo"][#"userDictionary"][#"response"][#"user"][#"firstName"]);

Related

Print UIImage metadata to label

I'm attempting to read the metadata produced by a UIImage when shot from the UIImagePicker, and I'm having some trouble.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
// get the metadata
NSDictionary *imageMetadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
NSLog (#"imageMetaData %#",imageMetadata);
This successfully prints the metadata dictionary to NSLog.
The issue I'm having is that I would like to access specific indices of the dictionary (such as FNumber, ISO, etc.) and print them to specific labels, but I can't figure out how to access the individual data.
Here is what I have tried so far to pull the data, but it doesn't seem to find the key (it returns as NULL):
NSLog(#"ISO: %#", imageMetadata[#"ISOSpeedRatings"]);
Based off of what NSLog prints for the dictionary, it seems as if there may be dictionaries within the dictionary, and that's what's throwing me off.
Here's what gets printed for the metadata:
imageMetaData {
DPIHeight = 72;
DPIWidth = 72;
Orientation = 6;
"{Exif}" = {
ApertureValue = "2.27500704749987";
BrightnessValue = "-0.6309286396300304";
ColorSpace = 1;
DateTimeDigitized = "2015:04:01 10:33:37";
DateTimeOriginal = "2015:04:01 10:33:37";
ExposureBiasValue = 0;
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666666666666667";
FNumber = "2.2";
Flash = 24;
FocalLenIn35mmFilm = 29;
FocalLength = "4.15";
ISOSpeedRatings = (
320
);
LensMake = Apple;
LensModel = "iPhone 6 back camera 4.15mm f/2.2";
LensSpecification = (
"4.15",
"4.15",
"2.2",
"2.2"
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneType = 1;
SensingMethod = 2;
ShutterSpeedValue = "3.907056515078773";
SubjectArea = (
1631,
1223,
1795,
1077
);
SubsecTimeDigitized = 705;
SubsecTimeOriginal = 705;
WhiteBalance = 0;
};
"{MakerApple}" = {
1 = 2;
14 = 0;
2 = <0f000b00 06000900 04005000 a900b100 b700bb00 c400cd00 cd00a400 b100c700 14000b00 05000900 06000a00 8a00a800 b000b800 c300cb00 c900cd00 b300a600 2f000700 06000700 0a000400 3500a400 ab00b300 bc00c300 cf00d300 b4007f00 3f000700 09000700 0a000700 05007100 a100af00 b500c200 ce00cd00 a9006b00 1f000a00 0b000900 0a000c00 05001e00 9c00aa00 b400c200 cc00d000 d4005700 2b001900 0d001000 10000d00 08000600 5b00a700 b300bf00 cb00d500 e3008600 eb002800 1a001700 14000c00 0b000700 10009400 b100c000 ce00e000 f400bd00 cf013e00 2a001200 17000f00 0d000800 07004200 b100c000 d300e900 fd000401 ff011101 1d000700 16001400 09000700 07000900 8900bf00 d800ec00 07011f01 10021102 39000b00 10001900 0e000800 0a000700 2c00bf00 dd00f400 0b012401 1e023802 1f010d00 07001900 16000c00 0c000800 21007000 c500f400 0a012e01 10022202 01022500 08001000 18001100 0d001800 1601cc00 d100eb00 09012201 fb011002 26020401 0f000700 16001400 3200e801 6001b000 ce00f400 08011601 e1010602 1a020302 23001700 21002300 84009300 9f00ad00 bf00e800 02011401 ca01fc01 19024002 08013d00 3500ca00 7c009200 9e00ab00 c200d700 f8000a01 b401f101 1b024802 28023000 4a007f00 7f008e00 a000b100 bd00d000 ec00fe00>;
3 = {
epoch = 0;
flags = 1;
timescale = 1000000000;
value = 777291330499583;
};
4 = 1;
5 = 128;
6 = 123;
7 = 1;
8 = (
"0.2226092",
"-0.5721548",
"-0.7796207"
);
9 = 275;
};
"{TIFF}" = {
DateTime = "2015:04:01 10:33:37";
Make = Apple;
Model = "iPhone 6";
Software = "8.1.2";
XResolution = 72;
YResolution = 72;
};
}
Is the data I'm looking for within another NSDictionary named Exif? And if so, how do I access it?
#david strauss can you try this once
- (void) saveImage:(UIImage *)imageToSave withInfo:(NSDictionary *)info{
// Get the assets library
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Get the image metadata (EXIF & TIFF)
NSMutableDictionary * imageMetadata = [[info objectForKey:UIImagePickerControllerMediaMetadata] mutableCopy];
// add GPS data
CLLocation * loc = <•••>; // need a location here
if ( loc ) {
[imageMetadata setObject:[self gpsDictionaryForLocation:loc] forKey:(NSString*)kCGImagePropertyGPSDictionary];
}
ALAssetsLibraryWriteImageCompletionBlock imageWriteCompletionBlock =
^(NSURL *newURL, NSError *error) {
if (error) {
NSLog( #"Error writing image with metadata to Photo Library: %#", error );
} else {
NSLog( #"Wrote image %# with metadata %# to Photo Library",newURL,imageMetadata);
}
};
// Save the new image to the Camera Roll
[library writeImageToSavedPhotosAlbum:[imageToSave CGImage]
metadata:imageMetadata
completionBlock:imageWriteCompletionBlock];
[imageMetadata release];
[library release];
}
The metadata dictionary as you've noticed consists of several dictionaries.
So to answer your question - yes, if you're looking for specific values you can access the inner dictionaries. Also, you'd better use the proper keys from ImageIO constants; for example:
NSLog(#"%#", imageMetadata[(NSString*)kCGImagePropertyExifDictionary][(NSString*)kCGImagePropertyExifISOSpeedRatings]);
Or, you can use a key-path:
NSString *keyPath = [NSString stringWithFormat:#"%#.%#",
(NSString*)kCGImagePropertyExifDictionary, (NSString*)kCGImagePropertyExifISOSpeedRatings];
NSLog(#"%#", [imageMetadata valueForKeyPath:keyPath]);
your all required data is within this dictionary only.
you can use json formatter to see the exact location of your data.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: imageMetadata
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
}
after this get the exact location of your data from json

ios edit phone number in contact programmatically [duplicate]

I'm trying to replace an specific phone number for an specific contact programmatically in iOS, taking the contacts form address book.
I don't know why I can't save the new phone number and refresh the address book to show the change.
I'm doing this:
+(BOOL) changeContactPhoneNumber:(NSString *) phoneSought
forThis:(NSString *) newPhoneNumber{
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef contactSelected;
CFStringRef mobileLabelNumber;
CFErrorRef error = nil;
// Do whatever you want here.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (int i = 0; i < nPeople; i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSString* mobilePhoneNumber=#"";
if (ABMultiValueGetCount(phones) > 0) {
for (int i=0; i < ABMultiValueGetCount(phones); i++) {
[mobilePhoneNumber release];
mobilePhoneNumber = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
if([mobilePhoneNumber isEqualToString:phoneSought]){
contactSelected = ref;
mobileLabelNumber = ABMultiValueCopyLabelAtIndex(phones, i);
}
}
}
}
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABPersonPhoneProperty);
bool didAddPhone = ABMultiValueAddValueAndLabel(phoneNumberMultiValue ,(__bridge CFTypeRef)newPhoneNumber,mobileLabelNumber, NULL);
if(didAddPhone){
ABRecordSetValue(ABAddressBookGetPersonWithRecordID(addressBook, contactSelected),
kABPersonPhoneProperty,
phoneNumberMultiValue,
nil);
bool bSuccess = ABAddressBookSave(addressBook, &error);
if (!bSuccess) {
NSLog(#"Could not save to address book: %#", error);
} else {
return YES;
}
} else {
NSLog(#"Error editing phone number: %#", error);
error = nil;
}
return NO;
}
You should debug your code and try to figure out whether the format of the phone numbers you are providing to the method are matching or not.
For e.g. when i am logging my contact list phone numbers these are results
Number...555-478-7672
Number...(408) 439-5270
Number...(408) 555-3514
Number...888-555-5512
Number...888-555-1212
Number...555-522-8243
Number...(555) 766-4823
Number...(707) 555-1854
Number...555-610-6679
And i was comparing these number against unformatted number string.
Secondly
ABRecordSetValue(ABAddressBookGetPersonWithRecordID(addressBook, contactSelected),
kABPersonPhoneProperty,
phoneNumberMultiValue,
nil);
Whose actual declaration is
ABRecordSetValue(ABRecordRef record, ABPropertyID property, CFTypeRef value, CFErrorRef* error);
Although ABAddressBookGetPersonWithRecordID returns a ABRecordRef but you already have ABRecordRef contactSelected; so in my view you should use
ABRecordSetValue(contactSelected,kABPersonPhoneProperty,phoneNumberMultiValue,nil);
Please correct me if i am wrong or have misunderstood your code!

flickr.photoset.getlist json parsing in ios

I want to parse a array of json dictionary which is returned to me using the method flickr.photosets.getlist.I am using objectiveFlickr api.
This is my json
"_text" = "\n\n";
photosets = {
"_text" = "\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\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n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n";
cancreate = 1;
page = 1;
pages = 1;
perpage = 871;
photoset = (
{
"_text" = "\n\t\t\n\t\t\n\t";
"can_comment" = 1;
"count_comments" = 0;
"count_views" = 0;
"date_create" = 1403859842;
"date_update" = 0;
description = {
"_text" = "Uploaded from my iPhone/iPod Touch";
};
farm = 6;
id = 72157645380087391;
"needs_interstitial" = 0;
photos = 1;
primary = 14514940751;
secret = ebc107d841;
server = 5237;
title = {
"_text" = banjara;
};
videos = 0;
"visibility_can_see_set" = 1;
},
{
"_text" = "\n\t\t\n\t\t\n\t";
"can_comment" = 1;
"count_comments" = 0;
"count_views" = 0;
"date_create" = 1403849913;
"date_update" = 0;
description = {
"_text" = "Uploaded from my iPhone/iPod Touch";
};
farm = 4;
id = 72157645380777662;
"needs_interstitial" = 0;
photos = 1;
primary = 14516264624;
secret = 70097bb15c;
server = 3867;
title = {
"_text" = iuggjkd;
};
videos = 0;
"visibility_can_see_set" = 1;
}
);
};
I am stuck in this for hours.Can u suggest me how to deal with this.
Thanks for the reply
Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.You can use NSDictionary or NSArray as per your requirement.
This is what I am doing to fetch images from JSON and showing in my app. Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"yourKeyField"];
Now you have the values in your demoArray.
Hope this helps.

Passing NSMutableArray to the server

I'm currently working with AddressBook in iOS, I'm getting the emails from all the contacts of the user, and putting them into the NSMutableArray. Now I must to pass this array to the server[PHP]. But the problem that is the emails are in the double quotes, so it looks something like this:
(
"user#gmail.com",
"user2#gmail.com",
"user3#gmail.com"
)
That is my code:
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
_usersEmails = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++) {
NSData* email = [(__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j) dataUsingEncoding:NSUTF8StringEncoding];
[_usersEmails addObject:email];
}
CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);
Web-programmer that was implementing the server-side, told me that I must to pass the array of strings without the double quotes.
How can I remove the double quotes in each string of my array?
Update:
This is the piece of the actual data that had been received by the server:
\"user#gmail.com\"','\"user#gmail.com\"','\"user#gmail.com\"','\"user#me.com\"
You can use the NSString's substringFromIndex and substringToIndex methods to eliminate the first and last characters. Something like [[string substringToIndex:string.length - 1] substringFromIndex:1];
EDIT:
And can't you check/remove the quotation marks here:
NSData* email = [(__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j) dataUsingEncoding:NSUTF8StringEncoding];
by writing something like:
NSString *string = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
NSString *stringWithoutQuotations = [[string substringToIndex:string.length - 1] substringFromIndex:1];
NSData* email = [stringWithoutQuotations dataUsingEncoding:NSUTF8StringEncoding];
The quotes are shown when NSString is printed to the console--I don't think your strings actually contain quotation marks..
Try using the debugger inspector instead to double-check.
Do this:
for (NSString* aString in _userEmails) {
NSLog(#"The string is %#", aString);
}
You will see that there are no quotes.

How to find out the parent groups of a person?

On MAC platform, the ABPerson class has a parentGroups attribute, which tells us which groups the person belongs to. But On IOS platform, there is no such method or property..
How to find out the parent groups of a person? Do I needs to search through all groups one by one?
Thanks.
another thread mentioned ABPersonCopyParentGroups -- but this is wrong -n.a. on ios.
there is no api call so doing this directly is needed
ABRecordRef personToFind = ....
ABRecordID id = ABRecordGetRecordID(personToFind);
NSArray *groups = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllGroups(bookRef);
for(ABGroupRef group in groups) {
NSArray *members = (__bridge_transfer NSArray*)ABGroupCopyAllMembers(group);
for(ABRecordRef member in members) {
if(id == ABRecordGetRecordID(member){
NSLog(#"found in group %#!", ABGroupCopyProperty(group, kABGroupName);
break;
}
}
}
*typed inline, no guarantees -- there are likely typos!
I had difficulties to use Daij-Djan answer, so I rewrote it:
CFArrayRef groupsRef = ABAddressBookCopyArrayOfAllGroups(myAddressBook);
if(groupsRef) {
NSUInteger groupsCount = CFArrayGetCount(groupsRef);
for(NSUInteger idx = 0; idx < groupsCount; ++idx) {
ABRecordRef groupRef = CFArrayGetValueAtIndex(groupsRef, idx);
ABRecordID groupID = ABRecordGetRecordID(groupRef);
CFArrayRef membersRef = ABGroupCopyArrayOfAllMembers(groupRef);
if(membersRef) {
NSUInteger membersCount = CFArrayGetCount(membersRef);
for(NSUInteger idx = 0; idx < membersCount; ++idx) {
ABRecordRef memberRef = CFArrayGetValueAtIndex(membersRef, idx);
ABRecordID memberID = ABRecordGetRecordID(memberRef);
// your code
}
CFRelease(membersRef);
}
}
CFRelease(groupsRef);
}
I scan all groups and people in them, and save person recordID and group recordID to a NSDictionary.
I keep this NDDictionary till app gone, so just need to lookup this NSDictionary for person's group ID.
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
CFArrayRef allGroup = ABAddressBookCopyArrayOfAllGroups( AddressBookManager.addressBook );
CFIndex nGroup = ABAddressBookGetGroupCount(AddressBookManager.addressBook);
NSMutableArray *array = [[NSMutableArray alloc] init];
for (CFIndex index = 0; index < nGroup; index ++)
{
ABRecordRef group = CFArrayGetValueAtIndex(allGroup, index);
ABRecordID groupID = ABRecordGetRecordID(group);
CFArrayRef allPeople = ABGroupCopyArrayOfAllMembers(group);
CFIndex nPeople = CFArrayGetCount(allPeople);
for( CFIndex personIndex = 0; personIndex < nPeople; personIndex++ )
{
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, personIndex );
ABRecordID personID = ABRecordGetRecordID(person);
NSNumber *value = [NSNumber numberWithInt:groupID];
NSString *key = [NSString stringWithFormat:#"%d", personID];
[dic setValue:value forKey:key];
}
CFRelease(allPeople);
}

Resources