Trying to parse twitter trends - iphone

Im trying to parse twitter trends but i keep getting a parser error at "as_of". anyone know why this is happening?
EDIT:
Here is the code im using
NSMutableArray *tweets;
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
trendsArray = [[NSMutableArray alloc] initWithArray:[CCJSONParser objectFromJSON:[NSString stringWithContentsOfURL:url encoding:4 error:nil]]];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i = 0; i < [trendsArray count]; i++) {
dict = [[NSMutableDictionary alloc] init];
//[post setObject: [[currentArray objectAtIndex:i] objectForKey:#"query"]];
[dict setObject:[trendsArray objectAtIndex:i] forKey:#"trends"];
//[dict setObject:[trendsArray objectAtIndex:i] forKey:#"query"];
//[post setObject:[trendsArray objectAtIndex:i] forKey:#"as_of"];
[tweets addObject:dict];
//post = nil;
}

I'm not exactly sure what your problem could be but I've had a play with the twitter api and CCJSON and have got some sample code that seems to work. If you cut and paste it into the applicationDidFinishLaunching method of a new project and include the CCJSON files it will just work (hopefully).
This code will take the trends json from twitter, output the as_of value and create an array of trends.
// Make an array to hold our trends
NSMutableArray *trends = [[NSMutableArray alloc] initWithCapacity:10];
// Get the response from the server and parse the json
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:4 error:nil];
NSDictionary *trendsObject = (NSDictionary *)[CCJSONParser objectFromJSON:responseString];
// Output the as_of value
NSLog(#"%#", [trendsObject objectForKey:#"as_of"]);
// We also have a list of trends (by date it seems, looking at the json)
NSDictionary *trendsList = [trendsObject objectForKey:#"trends"];
// For each date in this list
for (id key in trendsList) {
// Get the trends on this date
NSDictionary *trendsForDate = [trendsList objectForKey:key];
// For each trend in this date, add it to the trends array
for (NSDictionary *trendObject in trendsForDate) {
NSString *name = [trendObject objectForKey:#"name"];
NSString *query = [trendObject objectForKey:#"query"];
[trends addObject:[NSArray arrayWithObjects:name, query, nil]];
}
}
// At the point, we have an array called 'trends' which contains all the trends and their queries.
// Lets see it . . .
for (NSArray *array in trends)
NSLog(#"name: '%#' query: '%#'", [array objectAtIndex:0], [array objectAtIndex:1]);
Hope this is useful, comment if you have any questions,
Sam
PS I used this site to visualise the JSON response - it made it much easier to see what is going on - I just cut and paste the JSON from twitter into it :)

Related

Extracting Unique Objects from a Data Array

I want to add names in a data array only if the name does not previously exist in the data array. When I attempt to print these names, I do get repetitions. Is there a way to solve this?
-(NSMutableArray *)autoComplete
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#45.25,-95.25&limit=100&client_id=Von0J4Bu6INiez5bGby2R&client_secret=50sUjSbg7dba8cQgtpdfr5Ns7wyYTqtmKpUU3khQ",kWSURL];
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"success"])
{
NSArray *responceArray = [returnDict objectForKey:#"response"];
for (NSDictionary *dict in responceArray) {
placeDC *place = [[placeDC alloc]init];
NSDictionary *placeDict = (NSDictionary *)[dict objectForKey:#"place" ];
NSDictionary *loctionDict =(NSDictionary *)[dict objectForKey:#"loc"];
NSString * name =[placeDict objectForKey:#"name"];
NSString * stateFull =[placeDict objectForKey:#"stateFull"];
NSString * countryFull =[placeDict objectForKey:#"countryFull"];
NSString *latitude =[loctionDict objectForKey:#"lat"];
NSString *longitude = [loctionDict objectForKey:#"long"];
place.placeNmae=name;
place.countryFullName=countryFull;
place.stateFullName=stateFull;
NSLog(#"%# ",stateFull);
place.latitude=[latitude doubleValue];
place.longitude=[longitude doubleValue];
[dataArray addObject:place];
}
}
return dataArray;
}
First Check that is there any response from the Server side or not, to check response use NSLog() or Break Points.
if response is ok then put a the following check your code
if (![dataArray containsObject:#"Some Name"])
{
// add Object
}
You could add the name NSString to an NSSet and check in every cycle whether it contains it or not.
Inside your if you could write something like:
NSArray *responceArray = [returnDict objectForKey:#"response"];
NSSet *names = [[NSSet alloc] init];
for (NSDictionary *dict in responceArray) {
NSDictionary *placeDict = (NSDictionary *)[dict objectForKey:#"place" ];
NSString * name =[placeDict objectForKey:#"name"];
if (![names containsObject:name]) {
[names addObject:name];
placeDC *place = [[placeDC alloc]init];
NSDictionary *loctionDict =(NSDictionary *)[dict objectForKey:#"loc"];
NSString * stateFull =[placeDict objectForKey:#"stateFull"];
NSString * countryFull =[placeDict objectForKey:#"countryFull"];
NSString *latitude =[loctionDict objectForKey:#"lat"];
NSString *longitude = [loctionDict objectForKey:#"long"];
place.placeNmae=name;
place.countryFullName=countryFull;
place.stateFullName=stateFull;
NSLog(#"%# ",stateFull);
place.latitude=[latitude doubleValue];
place.longitude=[longitude doubleValue];
[dataArray addObject:place];
}
}
Hope this helps!
Do one thing, add your dict in another array and search in this array that data already exist or not,
[tempAry addObject: dict];
and before insertion
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", name];
NSArray *filteredArray = [tempAry filteredArrayUsingPredicate:predicate];
if ([filteredArray count] == 0)
{
[dataArray addObject:place];
}
else{
//Already exist
}
Why don't you create a separate dictionary, as an ivar or property of you class, for storing our required value, say it as :
NSMutableDictionary *uniqueValueDict=[NSMutableDictionary new];
And keep storing your required value and key as:
[uniqueValueDict setObject:stateFull forKey:uniqueValueDict];
Your work will be done.
This is the easiest solution that i have applied and this should get you going in picking up unique elements out of array.
NSArray * claimedOfferArray = [[NSArray alloc]initWithObjects:#"A",#"B",#"A",#"C",#"B" nil];
NSArray * distinctArray = [[NSArray alloc]init];
distinctArray =[[NSSet setWithArray:claimedOfferArray] allObjects];
This code will also work with NSMutableArray
Let me know if it works for you..:).

How can i Parse xml data using GDataXML parser in iPhone application development?

-<stat>
<visitor>4</visitor>
<uniqueVisitor>2</uniqueVisitor>
<order>41</order>
<revenue>20658</revenue>
<conversionRate>48</conversionRate>
<newProduct>25</newProduct>
<outOfStockProduct>11</outOfStockProduct>
</stat>
From this xml i want to get the element name "visitor" & "uniqueVisitor" and their corresponding values using GDataXML parser.
Till now i have done these.
xmlFileLocation = [NSURL URLWithString:#"someurl....abc.php"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfURL:xmlFileLocation];
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
if (nil == xmlDocument) {
NSLog(#"could not load Branch.xml file");
}
else {
NSLog(#"Loading desire xml url for dashboard");
[self GDataXmlParser];
}
Using a tutorial i have done this till now. But now i want all of these element name and their corresponding values
-(void)GDataXmlParser{
NSArray *getData = [[xmlDocument rootElement]elementsForName:#"stat"];
records = [[NSMutableArray alloc]init];
tempArray = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in getData){
// What i have to do here????
}
}
look at the answer
NSLog(#"%#", xmlDocument.rootElement);
records = [[NSMutableArray alloc] init];
NSLog(#"Enering in the xml file");
NSString *Visitor = [[[xmlDocument.rootElement elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[xmlDocument.rootElement elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
for more see the link I am not able to parse xml data using GDataXML
Follow this link for tutorial :http://iphonebyradix.blogspot.com/2011/03/using-gdata-to-parse-xml-file.html
-(void) GDataXmlParser
{
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData
options:0
error:nil];
NSArray *temp = [xmlDocument.rootElement elementsForName:#"stat"];
NSMutableArray *records = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in temp)
{
[records addObject:e];
NSString *Visitor = [[[e elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[e elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
}
}
Hope it helps you. Happy iCoding.

Objective-C: NSDictionary and looping through inner NSDictionaries

I get the following NSDictionary when I parse a JSON response from my server:
(
{
fromUname = Ben;
id = ci2n9awef7tm7e142sx;
message = hi;
read = 1;
subject = hi;
time = 1316513972;
toUname = Jill;
},
{
fromUname = Eamorr;
id = asdf98s14u7tm7e142sx;
message = asdf;
read = 0;
subject = asdf;
time = 1316513322;
toUname = Jack;
}
)
I'm really struggling to extract the two subjects.
Here's what I've coded sofar (incomplete...):
...
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSLog(#"%#",obj);
NSLog(#"%d",[obj count]);
for(int i=0;i<[obj count];i++){
NSDictionary *message=[obj objectForKey:];
NSLog(#"%#",[message objectForKey:#"subject"]); //I'm stuck...
}
...
Can anyone give me some efficient way of extracting the subjects?
Many thanks in advance,
Its actually an NSArray of NSDictionaries. So to get the information, loop through the array and get the dictionary:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *obj = [parser objectWithString:[request responseString] error:nil];
NSLog(#"%# : %d",obj, [obj count]);
for (NSDictionary *dict in obj) {
NSLog(#"%#", [dict objectForKey:#"subject"]);
}

help me to get each elements from my json feed ? Please

I have this JSON data:
{
"data":{
"mat_149":{
"id":"149",
"title":"The closing of 40% profit within 9 month",
"teaser":"profit within 9 months only which is equal to 52% annual profit",
"body":" The auction was presented in a very high and commercial lands.\u000d\u000a",
"files":{
"911":{
"fid":"911",
"filename":"22.JPG",
"filepath":"http://mysite/files/22_0.JPG"
}
}
},
"mat_147":{
"id":"147",
"title":"Company launches the city ",
"teaser":"demands for distinguished lands.",
"body":" The area size is quare meters This is evident through projects and many other projects.\u000d\u000a\u000d\u000a",
"files":{
"906":{
"fid":"906",
"filename":"2D7z.jpg",
"filepath":"http://mysite/dlr/files/2D7Z.jpg"
}
}
},
"mat_link":"mysite.com/"
}
}
I'm parsing it like this with the json-framework:
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] ;
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:response error:nil];
NSLog(#"Data : %#", [data valueForKey:#"data"] );
I am getting Data:
NSLog(#"Data : %#", [data objectForKey:#"data"] );
I am getting the data , but what i should do to get the 'file' items like 'fid' , 'filename' , 'filepath' .How can i get each elements from 'Data' n 'files' and store into some NSStrings ........
Can someone point out what I have to do ? Please
They're all sub-dictionaries aren't they,
just try logging the whole dictionary so go:
NSLog(#"%#", data);
Then you can see the structure.
To get all the other data, you're going to need to create a data model to hold it all, which knows which keys to call to get the specific strings.
Or you could call [data allKeys];
Iterating through that, getting dictionaries that you have the model object for.
E.g:
//Somewhere you declare this
NSArray *keys = [data allKeys]
for (NSString *key in [data allKeys]) {
NSDictionary *oneObject = [dictionary objectForKey:key];
MyObjectModel *object = [[MyObjectModel alloc] init];
object.id = [oneObject objectForKey:#"id"];
object.title = [oneObject objectForKey:#"title"];
//etc
//then you create another dict for files
}
Alex

iPhone parsing url for GET params

I have an string which is got from parsing an xml site.
http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500
I want to have an NSString function that will be able to parse the value of c.
Is there a default function or do i have to write it manually.
You could use Regular expression via RegExKit Lite:
http://regexkit.sourceforge.net/RegexKitLite/
Or you could separate the string into components (which is less nice):
NSString *url=#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray *comp1 = [url componentsSeparatedByString:#"?"];
NSString *query = [comp1 lastObject];
NSArray *queryElements = [query componentsSeparatedByString:#"&"];
for (NSString *element in queryElements) {
NSArray *keyVal = [element componentsSeparatedByString:#"="];
if (keyVal.count > 0) {
NSString *variableKey = [keyVal objectAtIndex:0];
NSString *value = (keyVal.count == 2) ? [keyVal lastObject] : nil;
}
}
I made a class that does this parsing for you using an NSScanner, as an answer to the same question a few days ago. You might find it useful.
You can easily use it like:
URLParser *parser = [[[URLParser alloc] initWithURLString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"] autorelease];
NSString *c = [parser valueForVariable:#"c"]; //c=500
Try the following:
NSURL *url = [NSURL URLWithString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"];
NSMutableString *parameterString = [NSMutableString stringWithFormat:#"{%#;}",[url parameterString]];
[parameterString replaceOccurrencesOfString:#"&" withString:#";"];
// Convert string into Dictionary
NSPropertyListFormat format;
NSString *error;
NSDictionary *paramDict = [NSPropertyListSerialization propertyListFromData:[parameterString dataUsingEncoding:NSUTF8StringEncoding] mutabilityOption: NSPropertyListImmutable format:&format errorDescription:&error];
// Now take the parameter you want
NSString *value = [paramDict valueForKey:#"c"];
Here is the native iOS approach using NSURLComponents and NSURLQueryItem classes:
NSString *theURLString = #"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray<NSURLQueryItem *> *theQueryItemsArray = [NSURLComponents componentsWithString:theURLString].queryItems;
for (NSURLQueryItem *theQueryItem in theQueryItemsArray)
{
NSLog(#"%# %#", theQueryItem.name, theQueryItem.value);
}