Facebook results into an NSArray - iphone

I am using Facebook api to get user's friends name, UID and birthday. The problem I have is that how do I get to those values once I get the results back. Meaning, I want to get to username, birthdate for each returned value?
This code keeps crashing for me here
//set query
NSString *query = #"SELECT uid, name, birthday_date FROM user WHERE uid IN " #"(SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)";
// Set up the query parameter
NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
}
else {
NSLog(#"Result: %#", result);
NSArray *friendInfo = (NSArray *) [result objectForKey:#"data"];
NSArray *arryData3 = [[NSArray alloc] initWithArray:friendInfo];
NSLog(#"[friendInfo count]: %d ... [arryData3 count]: %d ...",[friendInfo count],[arryData3 count]);
for (int i=0; i<[arryData3 count]; i++) {
NSArray *bdayArray = [[NSArray alloc] initWithArray:[arryData3 objectAtIndex:i]];
//CODE CRASH HERE!!!!
NSString *bdayStr = [bdayArray objectAtIndex:0];
NSString *nameStr = [bdayArray objectAtIndex:1];
}
}
}];
This is what my crash log looks like
data(
{
"birthday_date" = "01/06";
name = "John Doe";
uid = 555555;
},
{
"birthday_date" = "09/01/1984";
name = "Mrs. Smith";
uid = 4444444;
},
)
[friendInfo count]: 2 ... [arryData3 count]: 2 ...
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSArray initWithArray:range:copyItems:]: array argument is not an NSArray'
*** First throw call stack:
(0x168f052 0x1cabd0a 0x167fe0b 0x15e8170 0x16ca2 0x27c03 0x26c7e 0x2444e 0x2927e 0x296e7 0xfc1a59 0xfbfe94 0xfc0eb7 0xfbfe4f 0xfbffd5 0xf04f6a 0x3964bbd 0x3a315ea 0x395b298 0x3a3116b 0x395b137 0x166397f 0x15c6b73 0x15c6454 0x15c5db4 0x15c5ccb 0x3bd1879 0x3bd193e 0x5cca9b 0x2038 0x1f95)

For anyone that maybe interested in future. This is how you get to individual values in the results of Facebook.
NSLog(#"Result: %#", result);
NSArray *friendInfo = (NSArray *) [result objectForKey:#"data"];
NSLog(#"[friendInfo count]: %d ....",[friendInfo count]);
for (int i=0; i<[friendInfo count]; i++)
{
NSMutableString *userNameStr = [NSMutableString stringWithFormat:#"%#", [[friendInfo objectAtIndex:i] objectForKey:#"name"]];
NSMutableString *userDateStr = [NSMutableString stringWithFormat:#"%#", [[friendInfo objectAtIndex:i] objectForKey:#"birthday_date"]];
NSLog(#"userNameStr: %# ... userDateStr: %# ...", userNameStr,userDateStr);
//From this point onwards you can put these individual strings into an array
//and if you had defined the array globally you can get to these results from
//any function in your code
}

The return is a dictionary, not an array.
Please read about NSDictionary and use it just like you used the result - objectForKey function. In this case the key is birthday_date and then name for the strings in the for function.
Liviu

Related

String not getting split giving unrecognized selector error

Trying to split the string in to array, but it is giving error "[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x11741b20'". The string contains the value, that comes from first index of array then the string needs to be split and store in array.
This is array value.
mcommarr:(
":comment",
":comment",
":comment"
NSString *strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
NSArray *arr2 = [str componentsSeparatedByString:#","];
Here is the complete method in which i am using this.
-(void)loadData:(int)indexVal;
{
indexVal=serialIndexVal;
serialIndexVal++;
NSLog(#"arrLike:%d", [self.mArrLike count]);
NSLog(#"arrPid:%d", [self.mArrPid count]);
status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
[self.activityIndicator startAnimating];
#try
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
self.mButtonsCommentsDict = [MyEventApi showComments:self.mButtonsPidDict];
self.mButtonsDict = [MyEventApi likeDislike:self.mButtonsUidDict post:self.mButtonsPidDict postStatus:self.mButtonsStatusDict];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.activityIndicator stopAnimating];
NSLog(#"buttons data dict:%#", self.mButtonsDict);
if([self.mButtonsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mArrLike addObject: #"0"];
[self.mArrDislike addObject: #"0"];
}else{
[self.mArrLike addObject: [self.mButtonsDict valueForKey:#"like"]];
[self.mArrDislike addObject: [self.mButtonsDict valueForKey:#"dislike"]];
}
if([self.mButtonsCommentsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mCommArrTot addObject: #"0"];
}
else{
self.dictComm = [self.mButtonsCommentsDict valueForKey:#"comments"];
[self.mCommArr addObject:[self.dictComm valueForKey:#"comment"]];
NSLog(#"count:%d",[self.mCommArr count]);
// NSString *strTot = [NSString stringWithFormat:#"%d",tot];
// [self.mCommArrTot addObject:strTot];
NSLog(#"dictcomm:%#", self.dictComm );
NSLog(#"mcommarr:%#", [self.mCommArr objectAtIndex:indexVal]);
strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
//NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
// NSArray *arr1 = [self string:strr];
// NSArray *splitArray=[self.mCommArr[0] componentsSeparatedByString:#","];
//[strr componentsSeparatedByString:#","];
// NSLog(#"arrSep:%#", arr1);
//int count = [arr1 count];
//NSLog(#"arrcount:%d", count);
// NSString *strTot = [NSString stringWithFormat:#"%d",count];
// [self.mCommArrTot addObject:strTot];
//NSLog(#"mcommarrtot:%#", [self.mCommArrTot objectAtIndex:indexVal]);
}
// NSLog(#"arrLike:%#", [self.mArrLike objectAtIndex:indexVal]);
// NSLog(#"arrDisLike:%#", [self.mArrLike objectAtIndex:indexVal]);
[self.mPublicFriendTable reloadData];
});
});
}
#catch (NSException *exception) {
NSLog(#"main: Caught %#: %#", [exception name], [exception reason]);
}
#finally {
}
}
It get killed when try to split. Why so, i am not getting. If anyone has faced such situation please guide what is wrong her.
You can split the string into an NSArray like below...
NSString *yourString = #"comment,comment,comment";
NSArray *strArray = [yourString componentsSeparatedByString:#","];
NSLog(#"\n\n Array is ==>> %#",strArray);
"[__NSArrayI componentsSeparatedByString:]:
Your error says you tried to send the above method to NSArray, which doesn't has.
As you want to split the array at index 0. you should probably do as :
NSArray *splitArray=[yourArray[0] componentsSeparatedByString:#","];
Here yourArray is the array that you get from Server.
NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
NSArray *arr2 = [strr componentsSeparatedByString:#","];
I think you are passing str right now, which can be an array (as your error points out).
Let me know the results.

Credential match from Plist

I have a plist with Array title and item0,item1,item2 is dictionary to store title and password of my app.now i want to check for signin process
now i Want to check for pass and items should be matched when i press submit button to login.i Tried the below code but xcode crashes
-(void)authenticateCredentials
{
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
if ([[[plistArray objectAtIndex:i]objectForKey:#"pass"]isEqualToString:emailTextFeild.text] && [[[plistArray objectAtIndex:i]objectForKey:#"title"]isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
return;
}
NSLog(#"INCorrect credentials");
}
}
and
-(NSArray*)readFromPlist
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"XYZ.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:documentPlistPath];
NSArray *valueArray = [dict objectForKey:#"title"];
return valueArray;
}
the xcode gets crashs ..please check in -(void)authenticateCredentials where i am incorrect?
AND
Crash when I select the submit button,Its wont give any output correct or incorrect in nslog and Xcode crash then , with errorr
2012-12-14 12:10:45.142 NavTutorial[1661:f803] emailEntry: hi#gmail.com.com
2012-12-14 12:10:45.145 NavTutorial[1661:f803] passwordEntry: hellohello
2012-12-14 12:10:45.153 NavTutorial[1661:f803] -[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1568cd8
2012-12-14 12:10:45.155 NavTutorial[1661:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1568cd8'
*** First throw call stack:
(0x14d7052 0x11c2d0a 0x14d8ced 0x143df00 0x143dce2 0x3981 0x14d8ec9 0x3735c2 0x37355a 0x418b76 0x41903f 0x417e22 0x39893f 0x398c56 0x37f384 0x372aa9 0x1bcdfa9 0x14ab1c5 0x1410022 0x140e90a 0x140ddb4 0x140dccb 0x1bcc879 0x1bcc93e 0x370a9b 0x211d 0x2095 0x1)
terminate called throwing an exception
and
two days ago this same code worked fine
and if i put Breakpoint for IF condition and later if fails just after if condition.
Modify your authenticateCredentials as shown below and check if it is working. If it is showing an error message as Error! Not a dictionary, you need to check if your plist is having correct structure. Mostly your [objDict objectForKey:#"pass"] is returning a different data type.
- (void)authenticateCredentials {
NSMutableArray *plistArray = [NSMutableArray arrayWithArray:[self readFromPlist]];
for (int i = 0; i< [plistArray count]; i++)
{
id object = [plistArray objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *objDict = (NSDictionary *)object;
if ([[objDict objectForKey:#"pass"] isEqualToString:emailTextFeild.text] && [[objDict objectForKey:#"title"] isEqualToString:passwordTextFeild.text])
{
NSLog(#"Correct credentials");
return;
}
NSLog(#"INCorrect credentials");
} else {
NSLog(#"Error! Not a dictionary");
}
}
}

combining 2 strings in objective-c

I have a problem when I try to combine 2 NSString
I extract 2 NSSring form a JSON and its diagrams are:
thumbList: ( "picture1.jpg", "picture2.jpg", "picture3.jpg" ... )
fullnameList: ("name1", "name2" , "name3" ... )
My intention is unite them into one using the following scheme:
("name1", "picture1.jpg", "name2", "picture2.jpg", "name3", "picture3.jpg"...)
NSArray *array_webdata=[[NSArray array] init];
NSString *searchStatus = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
array_webdata = [parsedata objectWithString:searchStatus error:nil];
//String with all data of each user
NSString *usersList = [array_webdata valueForKey:#"results"];
NSLog(#"\n results? = %# \n", usersList);
//String with thumbs
NSString *thumbList = [usersList valueForKey:#"thumb"];
NSLog(#"\n thumbs? = %# \n", thumbList);
//String with usernames
NSString *fullnameList = [usersList valueForKey:#"fullname"];
NSLog(#"\n fullnames? = %# \n", fullnameList);
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[fullnameList insertObjects:thumbList atIndexes:indexes];
NSLog(#"array: %#", fullnameList);
But when I try to execute shows the next error message: [__NSArrayI insertObjects:atIndexes:]: unrecognized selector sent to instance.
Can anyone help me?
You should use
NSMutableDictionary* dataDict = [NSMutableDictionary dictionaryWithObjects:picturesList forKeys:namesList];
// Whenever key needed for fetching record from Dictionary just write
NSArray* keyArr = [dataDict AllKey];
Now you have all key and you can fetch record with the help of above key.
All "unrecognized selector sent to instance." errors mean the same: you think some object has a method, but it really don't have it at runtime.
Due to the dynamic nature of Objective-C, if you're not sure of some object having a method you should always test it calling respondsToSelector: like this:
if ([myObj respondsToSelector:#selector(someMethod)]) {
[myObj someMethod];
}
In this case,
NSString *fullnameList = [usersList valueForKey:#"fullname"];
is a NSString. That class does not have a insertObjects:atIndexes: method. Maybe you have to declare it as an NSMutableArray

Items in NSDictionary returns NULL

I'm using MGTWitterEngine and I cannot figure out why my dictionary items are returning null.
I have this method:
- (void)searchResultsReceived:(NSArray *)searchResults forRequest:(NSString *)connectionIdentifier{
NSDictionary *result = [searchResults objectAtIndex:0];
NSString *fromUser = [result valueForKey:#"from_user"];
NSLog(#"from user: %#", fromUser);
}
And for some reason, my NSLog always displays "from user: NULL". I can do an NSLog of searchResults which dumps the contents of the search correctly, but I can't figure out how to parse the information. Any help would be greatly appreciated.
Look at this question: Parsing Search Result with MGTwitterEngine in Objective C
They use:
- (void)searchResultsReceived:(NSArray *)searchResults
forRequest:(NSString *)connectionIdentifier
{
if ([searchResults count] > 0)
{
NSDictionary *result = [searchResults objectAtIndex:0];
NSString *fromUser = [result valueForKey:#"from_user"];
NSString *fromUserID = [result valueForKey#"from_user_id"];
// ...
NSString *text = [result valueForKey#"text"];
NSLog(#"User %#(%#): %#", fromUser, fromUserID, text);
}
}
It is similar to your code with a check on searchResults count.

key values from an NSDictionary formatting with "()"

I'm trying to pull two values from this Dictionary, But the values I'm getting have "()" around them. Any Ideas what is causing this?
Here is the ServerOutput:
{"Rows":[{"userid":"1","location":"beach"}]}
Dictionary after JSON:
{
Rows = (
{
location = beach;
userid = 1;
}
);
}
This is what I'm getting:
location : (
beach
)
user Id : (
1
)
Both the userid and the location key values have the "()". Here is the code. Thanks a lot.
NSString *serverOutput= [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if(serverOutput > 1){
SBJSON *jsonFF = [[SBJSON new] autorelease];
NSError *error3 = nil;
NSDictionary *useridDict= [jsonFF objectWithString:serverOutput error:&error3];
NSLog(#"useridDict: %#",useridDict);
idreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"userid"];
locationreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"location"];
NSLog(#" user Id : %#", idreturn);
NSLog(#" location : %#", locationreturn);
Just to clarify what is going on. When parsing JSON {} gets returned as a dictionary and [] gets retured as an array. So we have useridDict an NSDictionary containing the parsed data.
'useridDict' has one key Rows which returns an NSArray.
NSArray *useridArray = [useridDict objectForKey:#"Rows"];
Our useridArray has one element, an NSDictionary
NSDictionary *dict = [useridArray objectAtIndex:0];
This dict contains the two keys: location and userid
NSString *location = [dict objectForKey:#"location"];
NSInteger userid = [[dict objectForKey:#"userid"] intValue];
You can use like this.
idreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0]valueForKey:#"userid"];
locationreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0] valueForKey:#"location"];