Yahoo! weather in an iphone app - iphone

im developing an iphone app using yahoo weather service ( i have a key ).
i have 2 question :
can i use it in my app for commercial use ( like posting my app in appstore for free or no )
why the xml and json result are different :
http://weather.yahooapis.com/forecastrss?w=29330057&u=c
and
http://weather.yahooapis.com/forecastjson?w=29330057&u=c
there is any thing to do to much ( the first have the wanted location )?
thank you.

I suspect this is an issue with XML namespaces. Depending on the framework used and the actual full XML you'd have to access the elements by their namespace. You might want to switch to another, DOM-based framework (not using NSXMLParser), for example GDataXMLNode by Google. In a DOM-based framework you can access the individual nodes in a tree-like structure instead of building one on your own.
There are plenty of examples for this on the net, for example Building an RSS reader or How to read and write XML documents with GDataXML. But to give a quick example how this might look:
NSError *error = nil;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
if (doc == nil) { return nil; }
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
NSArray *lists = [doc nodesForXPath:#"/result/list" error:nil];
if ([lists count] > 0)
{
for (GDataXMLNode *list in lists) {
int listid = [self integerInNode:list forXPath:#"listid"];
NSString *listname = [self stringInNode:list forXPath:#"name"];
[result setValue:[NSNumber numberWithInt:listid] forKey:listname];
}
}
[doc release];
return [result autorelease];

Yes, Yahoo! let you use their APIs under a fair-use policy, even commercially. Don’t be an ass and give them enough props though, e.g. their icon or logo with a link to their website.
I don’t think that it’s important to know why there are differences in both output formats. Use what is better / easier for you. Personally I prefer using JSON and Apple’s NSJSONSerialization class.

Related

MapKit in iOS 6 - How to Find Places Nearby...?

Using MapKit in iOS 6, how am I'm supposed to get nearby locations without having their specific coordinates? I'm also unsure if it's still possible...err...allowed...to use Google Maps API to accomplish this goal, as this is the only way I can think of to do this. I know everything is still in beta, but I've still found no information anywhere about this topic, on forums, in Apple's new MapKit Documentation, anywhere. All I want to do is perform a search for locations (let's say, parks, for example) within 'x' miles of the user's location.
It seems that since Apple has developed their own Maps application, they should have a way to accomplish this using MapKit or Core Location...right?
Try with this code. This may help to you.
URLManager *urlmanager = [[URLManager alloc] init];
urlmanager.delegate = self;
urlmanager.responseType = JSON_TYPE;
urlmanager.commandName = #"Search";
NSString *locationString = [NSString stringWithFormat:#"%f,%f",latitude,longitude];
//Location where you want to search
NSString *key = #"AIzaSyCNRpero6aM451X0IfgFHAd-Y3eJUssqoa8`enter code here`0E";
//This is the secret key which you will get from the Google API Console when you register your app.
NSString *radiuos = #"15000";
//This is the area within which you want to search
NSString *keyword = #"Hotel";//Search keyword you want to search
NSMutableDictionary *arguments = [[NSMutableDictionary alloc] init]; // zero argument
[arguments setValue:key forKey:#"key"];
[arguments setValue:locationString forKey:#"location"];
[arguments setValue:radiuos forKey:#"radius"];
[arguments setValue:#"true" forKey:#"sensor"];
[arguments setValue:keyword forKey:#"keyword"];
NSLog(#"Arguments are %#",arguments);
[urlmanager urlCallGetMethod:[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json"] withParameters:arguments];

Unable to get data from a div tag using HTML parsing (hpple) in iPhone

I am trying to parse the below link using hpple:
http://www.decanter.com/news/wine-news/529748/mimimum-pricing-opponents-slam-cameron-speech
Code:
- (void)parseURL:(NSURL *)url {
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser searchWithXPathQuery:#"<div class=\"body\" id=\"article-529748-body\">"];
NSLog(#"elements %#",elements);
TFHppleElement *element = [elements objectAtIndex:0];
NSString *myTitle = [element content];
[xpathParser release];
}
but it is crashing. Crash Report:
XPath error : Invalid expression
<div class="body" id="article-529748-body">
^
XPath error : Invalid expression
<div class="body" id="article-529748-body">
^
How to solve this issue? why my elements array is empty? Am I parsing in a wrong way? I want to get the information available in that div tag.
Check that your elements array is not empty
- (void)parseURL:(NSURL *)url {
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser searchWithXPathQuery:#"<div class=\"body\" id=\"article-529748-body\">"];
NSLog(#"elements %#",elements);
if([elements count]){
TFHppleElement *element = [elements objectAtIndex:0];
}
NSString *myTitle = [element content];
[xpathParser release];
}
Try changing this:
NSArray *elements = [xpathParser searchWithXPathQuery:#"<div class=\"body\" id=\"article-529748-body\">"];
To:
NSArray *elements = [xpathParser searchWithXPathQuery:#"//div [#class='body'] [#id=\'article-529748-body\']"];
Writing this (2 years later!) in case it's useful to someone else with a similar problem.
In order to parse the html within the div, you need to
use syntax similar (single-quotes don't need to be escaped) to that quoted by JamMySon on this page
remember that [element content] only gives you the content( if any) for that node , NOT its children.
Because of this you may need to use recursion to walk though the div's node-tree.
Code (ARC):
- (void) decanterHpple{
NSURL *url = [NSURL URLWithString:#"http://www.decanter.com/news/wine-news/529748/mimimum-pricing-opponents-slam-cameron-speech"];
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple *pageParser = [TFHpple hppleWithHTMLData:htmlData];
NSString *queryString = #"//div[#id='article-529748-body']";//1.works with unescaped single-quotes(') AND 2.No need for class='' when using id=''
NSArray *elements = [pageParser searchWithXPathQuery:queryString];
//old code ~ slightly amended
if([elements count]){
TFHppleElement *element = [elements objectAtIndex:0];
NSString *myTitle = [element content];
NSLog(#"myTitle:%#",myTitle );
}
//new code
NSString *theText = [self stringFromWalkThruNodes:elements];
NSLog(#"theText:%#",theText );
}
using this recursive method:
- (NSString*) stringFromWalkThruNodes:(NSArray*) nodes {
static int level = 0;//level is only useful for keeping track of recursion when stepping through with a breakpoint
level++;//put breakpoint here...
NSString *text = #"";
for (TFHppleElement *element in nodes){
if (element.content) {
text = [text stringByAppendingString:element.content];
}
if (element.children) {
NSString *innerText = [self stringFromWalkThruNodes:element.children];
text = [text stringByAppendingString:innerText];
}
}
level--;
return text;
}
This gives the output:
2014-10-22 19:44:07.996 Decanted[10148:a0b] myTitle:(null)
2014-10-22 19:44:07.997 Decanted[10148:a0b] theText:
On a visit to a hospital in north-east England, Mr Cameron is to call for the drinks industry to do more to tackle a problem which
costs the National Health Service £2.7bn a year.A ban on the sale of
alcohol below cost price - less than the tax paid on it - is set to be
introduced in England and Wales from 6 April, but ministers are
expected to push for a higher minimum price for drink.Opponents of a
minimum unit price say it is unfair because it penalises all drinkers,
not just binge or problem drinkers.Responding to the Prime Minister’s
comments, Wine and Spirit Trade Association spokesman Gavin Partington
reiterated the drinks indusry’s commitment ‘to helping the Government
tackle alcohol misuse, alongside other stakeholders.‘This is why we
are working hard through the Public Health Responsibility Deal on a
range of initiatives to promote responsible drinking.’These
initiatives, Partington said, include the expansion of Community
Alcohol Partnerships across the UK and a national campaign by
retailers to raise consumer awareness about the units of alcohol in
alcoholic drinks.Partington said, ‘Unlike these measures, minimum unit
pricing is a blunt tool which would both fail to address the problem
of alcohol misuse and punish the vast majority of responsible
consumers. As Government ministers acknowledge, it is also probably
illegal'.Decanter is also against the scheme, calling it
‘fundamentally flawed.’‘The real problem,’ editor Guy Woodward has
said, ‘lies with supermarkets who use wine as a loss-leader, slashing
margins, bullying suppliers and dragging down prices in order to
attract customers…Selling wine at a loss helps neither consumers nor
the trade.’Other opponents of the scheme include the British Beer and
Pub Association, which told the BBC there was ‘a danger it would be
done through higher taxation, which would be hugely damaging to
pub-goers, community pubs and brewers, costing thousands of vital
jobs.’It is thought any move toward minimum pricing could also be
illegal under European competition law, which is aimed at pushing down
prices for consumers and allowing firms to operate in a free
market.
PS. Only started playing with Hpple this p.m. after reading the aforementioned Wenderlich tutorial; I'm sure someone more experienced may come up with a more elegant solution!

how to get objects from a json array in iphone?

I am working on an iPhone app which involves using json-framework.I am getting array using NSURL
[{"firstName":"X","lastName":"Y","id":1},{"firstName":"A","lastName":"B","id":2}]
How can i get these 2 objects as like if i query for id=1, the O/P is
id=1
firstName:X
lastName:Y
and putting it in a table.
I am googling the stuff from many days but didn't get any solution.
Please help me out , explanation through code is appreciated.
Thank You.
If your target SDK is ios4 or higher, you can use this project
https://github.com/stig/json-framework/
Once you add the source to your project, just
#import "SBJson.h"
and convert your Json string as follows
jsonResponse = [string JSONValue];
The method will fail if you don't have the full Json array in your string, but you can keep appending strings until it doesn't fail
To follow up for codejunkie's request below
you can assume in your data structure that the jsonResponse is an NSArray
In other implementations take care to test the response for NSArray or NSDictionary
NSArray * myPeople = [string JSONValue];
NSMutableDictionary * organizedData = [[NSMutableDictionary alloc] init];
for (NSDictionary * p in myPeople) {
[organizedData setValue:p forKey:[p valueForKey:#"id"]];
}
// now you can query for an id like so
// [organizedData valueForKey:#"1"]; and your output will be what you wanted from the original question
// just don't forget to release organizedData when you are done with it
https://github.com/johnezang/JSONKit
I use this to get data from a webservice that spits out 50 records each having another 20 internal elements similar to the one you specify...
I use the JSONKit in the following manner..(Had a look at SBJson a lot of user but i got confused from the word go.)
JSONDecoder *jArray = [[JSONDecoder alloc]init];
NSMutableArray *theObject = [[NSMutableArray alloc] init];
theObject = [jArray objectWithData:theResponseData];//objectWithString:theResponseString
NSMutableArray *csArray = [[NSMutableArray array] retain] ;
for(id key in theObject)
{
if([key valueForKey:#"firstName"] != Nil)
{
........
}
if([key valueForKey:#"lastName"] != Nil)
{
........
}
}
check it out and let me know if it works or not.. By the way Great responses guys... Good

MGTwitterEngine is not returning re-tweets, only “original” tweets

I’m a newbie to iPhone app development and trying to create a Twitter-based iPhone app.
I’m using MGTwitterEngine to search and retrieve the timeline of people I follow.
The method I’m using is:
[twitterEngine getFollowedTimelineSinceID:0 startingAtPage:0 count:100];
Things are working great, however there are a couple of things I struggle with:
I’m only getting tweets originally posted by my followed list, no re-tweets at all. I would really like to get all tweets (original and re-tweets) at the same call, but if I need to perform two requests (one for tweets and one for re-tweets) that will work fine for me as well.
I’m getting back less than 100 tweets, though I know for a fact that people I follow have posted more than that. Any idea how to solve it?
Several people have mentioned MGTwitterEngine is lacking re-tweeting functionality. I’m not trying to re-tweet but simply to get the complete timeline (including re-tweets by people I follow).
Many thanks!
Look at this https://dev.twitter.com/docs/api/1/get/statuses/home_timeline
Specifically look at the part that say :
Include_RTS : When set to either true, t or 1,the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets...
Now in the getFollowedTimelineSinceID method you'll need to create a new object for the params dictionary something along these lines
[params setObject:[NSString stringWithFormat:#"%#", #"true"] forKey:#"Include_RTS"];
Per #bizsytes suggestion I have done two modifications to MGTwitterEngine’s
getFollowedTimelineSinceID method:
Changed the path string from #statuses/friends_timeline.%# to #statuses/home_timeline.%#
Added the Include_RTS object
Apparently it solved both my problems (retweets & number of statuses retrieved).
Now the method now looks like the following:
- (NSString *)getAllFollowedTimelineSinceID:(unsigned long)sinceID withMaximumID:(unsigned long)maxID startingAtPage:(int)page count:(int)count
{
NSString *path = [NSString stringWithFormat:#"statuses/home_timeline.%#", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", sinceID] forKey:#"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", maxID] forKey:#"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:#"%d", page] forKey:#"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:#"%d", count] forKey:#"count"];
}
[params setObject:[NSString stringWithFormat:#"%#", #"true"] forKey:#"Include_RTS"];
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterFollowedTimelineRequest
responseType:MGTwitterStatuses];
}

Simple Way to Strip Tags In Obj-C

I am just learning objective-c and iPhone development, and I am really struggling with some very basic tasks. I am only on my 3rd day of the learning process - so that is to be expected somewhat. I'm still almost ashamed to ask such a simple question.
Anyhow, here's my question. I have a .NET web service which I call using a GET for http://somehost/ping
it returns 'pong'
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">pong</string>
The simplest of test cases.
Back on the iPhone when I retrieve the URL I have the above string as a result. I only want the 'pong' part. This seems like programming 101, but I can't seem to find a simple example of how to do it that doesn't involve defining delagates or other seemingly complex processing steps.
The problem is simple enough, find the first '>' and extract everything from there until the first '<' as an NSString. That's all I need to do.
Does anyone have a basic example of how to do this?
This is dry-coded, and kinda ugly imho. But here is a more direct answer.
NSString *xml = #"<tag>pong</tag>";
NSRange range = [xml rangeOfString:#">"];
xml = [xml substringFromIndex:range.location + 1];
range = [substring rangeOfString:#"<"];
xml = [xml substringToIndex:range.location];
Hey Sylvanaar, I'm having to do similar types of parsing inside of the client. My general methodolgy for parsing xml responses is like this. I'm pretty sure the classes are available on iphone side too. Note: it may not be the absolute best method, but it does work.
- (id)initWithXMLNode:(NSXMLNode *)node {
self = [super init];
if (self != nil) {
NSError *error;
NSArray *objects;
// Get the fingerprint
objects = [node objectsForXQuery:#"for $fingerprint in ./Fingerprint return data($fingerprint)" error:&error];
handleErrorInInit(error)
fingerprint = getFingerprint(objects);
// Get the moduleName
objects = [node objectsForXQuery:#"for $moduleName in ./Foldername return data($moduleName)" error:&error];
handleErrorInInit(error)
moduleName = getNSString(objects);
}
return self;
}
Worth showing this too. Note that NSXMLDocuments are a subclass of NSXMLNodes.
- (NSXMLDocument *)xmlDocumentFromData:(NSData *)data {
NSError *error;
NSXMLDocument *document = [[[NSXMLDocument alloc] initWithData:data options:0 error:&error] autorelease];
if (error) {
[NSApp presentError:error];
return nil;
}
return document;
}
Sometimes a full on XML parse makes sense, but a quick index/substring routine can be appropriate as well:
NSRange startBracket = [xmlFragment rangeOfString:#">"];
if(startBracket.location != NSNotFound) {
NSRange endBracket = [xmlFragment rangeOfString:#"<"
options:0
range:NSMakeRange(startBracket.location,
[xmlFragment length] - startBracket.location)];
if(endBracket.location != NSNotFound) {
NSString *value = [[xmlFragment substringFromIndex:startBracket.location+1]
substringToIndex:endBracket.location];
// Do something with value...
}
}
(Not tested, needs more error handling, yadda yadda yadda..)