how to get the data from url in iphone - iphone

i am a new developer of iPhone.I have to get the names from this URL
Any API URL
in the table view.. how can i do this please help me..
i am try this by making connection but it is showing HTTP time out error .what is the reason by that and is there is any other way to get the data..
here is my connection code...
static NSString *feedURLString =
> #"http://www.XXXXX.com/XXXXXX/api/XXXXX.php?method=All";
> NSURLRequest *studentURLRequest =[NSURLRequest requestWithURL:[NSURL URLWithString:feedURLString]];
>self.studentFeedConnection =[[[NSURLConnection alloc] initWithRequest:studentURLRequest
> delegate:self] autorelease];
NSAssert(self.studentFeedConnection != nil, #"Failure to create URL connection.");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
> [[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(addstudent:) name:kAddstudentNotifm object:nil];
>[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(studentError:) name:kstudentErrorNotif object:nil];
> - (void)connection:(NSURLConnection *)connection
> didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
> if ((([httpResponse statusCode]/100) == 2) && [[response MIMEType]
> isEqual:#"application/atom+xml"]) {
> self.studentData = [NSMutableData data];
> }
else {
> NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(#"HTTP Error", #"Error message
> displayed when receving a connection error.")
>
> forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"HTTP" code:[httpResponse statusCode]userInfo:userInfo];
> [self handleError:error];
>}
}
>
> - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
> [studentData appendData:data];
}
>
> - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
> [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
> if ([error code] == kCFURLErrorNotConnectedToInternet) {
> // if we can identify the error, we can present a more precise message to the user.
> NSDictionary *userInfo = [NSDictionary dictionaryWithObject: NSLocalizedString(#"No Connection Error", #"Error message displayed when not connected to the Internet.")forKey:NSLocalizedDescriptionKey];
>NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
> [self handleError:noConnectionError];
>}
else {
>// otherwise handle the error generically
>[self handleError:error];
>}
> self.studentFeedConnection = nil;
}

Try using NSXMLParser
NSString *site = [NSString stringWithString:
#"http://www.XXXXX.com/XXX/api/XXXX.php?method=All"];
NSURL *url = [NSURL URLWithString:site];
NSXMLParser *myparser = [NSXMLParser initWithContentsOfURL:url];
myparser.delegate = self;
[myparser parse];
Make sure to implement
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;
- (void) parserDidEndDocument:(NSXMLParser *)parser;
Once you have the data parsed into an NSArray or NSDictionary you can use it as a data source in the UITableView

If you are getting an HTTP error, than chances are there is something wrong with the way in which you connect. Does your connection require authentication? If so you will need to implement:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *myCreds = [[NSURLCredential alloc] initWithUser:#"**USERNAME**" password:#"**PASSWORD**" persistence:NO];
[challenge.sender useCredential:myCreds forAuthenticationChallenge:challenge];
[myCreds release];
}
As for actually retrieving the data like you will need to use NSXML Parser, you can see the details for it here: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html. There are only 3 methods that you MUST implement, the remaining are just bonus. The three are
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
Ideally you know the structure of the XML that you are parsing as you will be required to identify the element/attribute name in the above functions. You can then store you data in an array, or whatever fits best.
You also have the option to use a 3rd party parser, there is a very good explanation/comparison of the various available parsers here: http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project
Hope this helps!

Related

How can i Parse this xml using NSXMLParser in ios?

<root>
<table name="radios">
<column name="nameradio">Radio1</column>
<column name="logo">http://app.syndicationradio.fr/demo/logo1.png</column>
<column name="stream">http://cloud2.syndicationradio.fr:8020</column>
<column name="twitter">http://www.twitter.com/#syndicationradio</column>
<column name="facebook">http://www.facebook.com/syndicationradio</column>
<column name="titre">http://app.syndicationradio.fr/demo/title.xml</column>
</table>
<table name="radios">
<column name="nameradio">Radio2</column>
<column name="logo">http://app.syndicationradio.fr/demo/logo1.png</column>
<column name="stream">http://cloud2.syndicationradio.fr:8020</column>
<column name="twitter">http://www.twitter.com/#syndicationradio</column>
<column name="facebook">http://www.facebook.com/syndicationradio</column>
<column name="titre">http://app.syndicationradio.fr/demo/title.xml</column>
</table>
</root>
Now please is there anybody help to find out that, how can i get those url from the xml data using NSXMLParser or any other xml parser suppose TBXML in IOS?
Edit: you can also give me example of libxml parser for this xml.
Thanks In Advance.
Try this:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSURL alloc] initWithString:#"yourURL"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
BOOL result = [parser parse];
// Do whatever with the result
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
NSLog(#"Did start element");
if ([elementName isEqualToString:#"root"]) {
NSLog(#"found rootElement");
return;
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(#"Did end element");
if ([elementName isEqualToString:#"root"]) {
NSLog(#"rootelement end");
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSString *tagName = #"column";
if ([tagName isEqualToString:#"column"]) {
NSLog(#"Value %#",string);
}
}
Ok you asked for a libxml example. I used it in a project but with TBXML instead of NSXMLParser because this one caused important problems of encoding and data retrieving.
First you have to download TBXML.m and TBXML.h files from the web and import them into your project. Then you also have to link libxml2.dylib to your project in Link Binary with Libraries.
Once this done, you will have to do this to retrieve your data (based on your XML source) :
NSData *xmlData = [NSData dataWithContentsOfURL:yourURL];
TBXML *tbxml = [TBXML newTBXMLWithXMLData:data error:nil];
[self getData:tbxml.rootXMLElement];
- (void) getData : (TBXMLElement *) element
{
do {
if([[TBXML elementName:element] isEqualToString:#"table"])
{
if([[TBXML elementName:element] isEqualToString:#"column"])
{
if([[TBXML attributeName:element] isEqualToString:#"nameradio"])
{
// You decide what to do here
}
}
}
if (element->firstChild) [self getData:element->firstChild];
} while(element = element->nextSibling);
}
You probably will have to change this code but here you have all the basic things you need.
This is how you can use NSXMLParser :
In your .h file declare :
NSMutableData *webPortFolio;
NSMutableString *soapResultsPortFolio;
NSURLConnection *conn;
//---xml parsing---
NSXMLParser *xmlParserPortFolio;
BOOL elementFoundPortFolio;
NSMutableURLRequest *req;
NSString *theXMLPortFolio;
NSString *strSoapMsg;
UIAlertView *alertView;
In your .m file use the following code:
-(void)callURL
{
//Your logic to call URL.
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webPortFolio = [[NSMutableData data] retain];
}
}
And to handle the response you can use following functions :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webPortFolio setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webPortFolio appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{
NSLog(#"error...................%#",[error description]);
[webPortFolio release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
//Check the request and returns the response.
NSLog(#"DONE. Received Bytes: %d", [webPortFolio length]);
theXMLPortFolio = [[NSString alloc]
initWithBytes: [webPortFolio mutableBytes]
length:[webPortFolio length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(#"shows the XML %#",theXMLPortFolio);
[theXMLPortFolio release];
if(xmlParserPortFolio)
{
[xmlParserPortFolio release];
}
xmlParserPortFolio = [[NSXMLParser alloc] initWithData: webPortFolio];
[xmlParserPortFolio setDelegate: self];
[xmlParserPortFolio setShouldResolveExternalEntities:YES];
[xmlParserPortFolio parse];
[webPortFolio release];
[connection release];
}
//---when the start of an element is found---
-(void) parser:(NSXMLParser *) parser
didStartElement:(NSString *) elementName
namespaceURI:(NSString *) namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict
{
if( [elementName isEqualToString:#"your_tag_name"])
{
if (!soapResultsPortFolio)
{
soapResultsPortFolio = [[NSMutableString alloc] init];
}
elementFoundPortFolio = TRUE;
NSLog(#"Registration...%#",soapResultsPortFolio);
}
else if([elementName isEqualToString:#"your_tag_name"])
{
elementFoundPortFolio = TRUE;
}
else if([elementName isEqualToString:#"your_tag_name"])
{
elementFoundPortFolio = TRUE;
}
else if([elementName isEqualToString:#"your_tag_name"])
{
elementFoundPortFolio = TRUE;
}
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
if (elementFoundPortFolio)
{
[soapResultsPortFolio appendString: string];
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(#"Parser error %# ",[parseError description]);
}
//---when the end of element is found---
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"your_tag_name"])
{
NSLog(#"display the soap results%#",soapResultsPortFolio);
}
else if([elementName isEqualToString:#"your_tag_name"])
{
//Perform required action
}
else if([elementName isEqualToString:#"your_tag_name"])
{
//Perform required action
}
else if([elementName isEqualToString:#"your_tag_name"])
{
//Perform required action
}
[soapResultsPortFolio setString:#""];
elementFoundPortFolio = FALSE;
}

parsing xml file with spanish (non UTF-8 format)

I need to parse xml files in spanish (were I don't have control over how are being generated). the parsing part works just fine but the problem is when the xml file has special characters for example:
Espectáculos
when is parse I get this:
áculos
I'm using CocoaXMLParser. any of you knows how can this been handle ?
this is my code:
-(void)getRss
{
NSString *urlString=#"http://mysite.com/content.xml";
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *rssRequest=[NSURLRequest requestWithURL:url];
self.contentConnection=[[NSURLConnection alloc]initWithRequest:rssRequest delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.dataResponse = [NSMutableData data];
NSLog(#"didReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_dataResponse appendData:data];
NSLog(#"didReceiveData");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading ");
[self parseContent];
}
-(void)parseContent
{
NSString *response = [[NSString alloc] initWithData:_dataResponse encoding:NSUTF8StringEncoding];
NSLog(#"data received %#", response);
NSLog(#"parse content ");
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:_dataResponse];
parser.delegate = self;
[parser parse];
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
self.currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementname isEqualToString:#"categoriaNoticias"])
{
self.validXML=YES;
NSLog(#"es xml valido");
}
else
{
self.validXML=YES;
}
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (_validXML) {
if ([elementname isEqualToString:#"titulo"])
{
NSString *string=_currentNodeContent;
NSLog(#"titulo %#", string);
}
if ([elementname isEqualToString:#"link"])
{
NSLog(#"titulo %#", _currentNodeContent);
}
}
}
I'll really appreciate any pointers
Assuming that your XML file is encoded in Latin-1 (ISO-8859-1), you fix the XML file on the fly:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
const char* xmlDecl = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\r\n";
self.dataResponse = [NSMutableData data];
[self.dataResponse appendBytes: xmlDecl length: strlen(xmlDecl)];
}
Please check what the effective encoding is and adapt the accordingly if needed.

How to set Parser Delegate to Self in ARC environment?

Hey I have used parsers in the past but never in an ARC environment. Now when I try and set my parser to self it gives me an error message and then doesn't parse my data. Anyone know what the problem is and how to solve it?
Here is the warning I get when I try to set the parser delegate to self:
Semantic Issue: Sending 'CharityController *const __strong' to parameter of incompatible type 'id<NSXMLParserDelegate>'
Here is my code:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connection == theConnection)
{
// do something with the data object.
//NSLog(#"Data from server is: %#",data);
NSString *test = [[NSString alloc]initWithData:data encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Data from server is: %#",test);
parser = [[NSXMLParser alloc] initWithData: data];
[parser setDelegate:self];
[parser parse];
}
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"root"]) {
currentStringValue = nil;
NSLog(#"I am inside the Parser at root!.");
return;
}
Did you use the protocol name in the interface definition to let the compiler know you conform to that particular protocol? Such as:
#interface CharityClass : NSObject <NSXMLParserDelegate>

iphone : NSXMLParser fails to identify HTML special entity &

I simply cannot get NSXMLParser to recognize &
here is my XML:
<?xml version="1.1" encoding="UTF-8"?>
<root>
<myURL>http://www.mywebsite.com/info?id=32&page=5</myURL>>
</root>
Here is my parsing code:
-(void)getXml {
NSURL *xmlurl = [[NSURL alloc] initWithString:#"http://www.mywebsite.com/myxml.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlurl];
[xmlParser setDelegate:self];
[xmlParser parse];
[xmlParser release];
[dataurl release];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSLog(#"Parser Error: %#", parseError);
}
- (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validError {
NSLog(#"Parser validation Error: %#", validError);
}
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(#"Parser started");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(#"Found key: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(#"Found Element: %#", string);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog("done"):
}
Here is my output:
Found key: root
Found key: myURL
Found element: http://www.mywebsite.com/info?id=32
Found element: page=5
Found element:
Found key: myURL
The parser is not recognizing the & correctly and is splitting up my url.
I have seen many Stack questions on this issue but none of them have helped and I have read the Apple docs on NSXMLParser as well. Am I missing something here?
I am building with iOS 5.0 to an iPhone 4
Thank you, this is a great insight into the parser process but there were problems using it, maybe due to the features of Xcode 4.5.1
It turned out that assigning a NSString like #"" to a NSMutableString makes it immutable. Instead to set the starting value for the tempString I've had to use
self.tempString = [[NSMutableString alloc] initWithString: #""];
and the parser:foundCharacters method becomes
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[self.tempString appendString:string];
currentNodeContent = (NSMutableString*) [self.tempString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
But that's one problem solved. Thanks.
According to the NSXMLParserDelegate documentation:
The parser object may send the delegate several
parser:foundCharacters: messages to report the characters of an
element. Because string may be only part of the total character
content for the current element, you should append it to the current
accumulation of characters until the element changes.
So the usual pattern of usage is to keep appending to a temporary string until the end of the element is reached:
.h
#property (nonatomic,retain) NSMutableString *tempString;
.m
#synthesize tempString;
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
self.tempString = #"";
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[self.tempString appendString:string];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
// do something with self.tempString
}

is there any dynamic xml parsing

how to parse if xml attributes changes...'
for example
<Root>
<child name="", age="",phone="",address=""/>
</Root>
this is my first request from iphone through webserver.... i parsed above xml...
after that when i request the same url .. which is updated now it my xml child tag changes.
<Root>
<child name="",age="",phone="",address="",office="",mobile="",location=""/>
</Root>
extra three attributes added..
what to do with this approach .. any example please send... thanks in advance
-(void)startParsingForSendFriendRequest:(NSString *)userID Friend:(NSString*)friendID
{
NSString *urlString =[NSStringstringWithFormat:#"http:///user_id=%#&friend_id=%#",userID,friendID];
////NSLog(#"urlString : %#",urlString);
NSURL *xmlURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *itemData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
//NSString *itemString = [[[NSString alloc] initWithBytes:[itemData bytes] length:[itemData length] encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"itemString : %#",itemString);
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:itemData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
////NSLog(#"parserDidStartDocument");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
////NSLog(#"parseErrorOccurred");
NSString * errorString = [NSString stringWithFormat:#"Error (Error code %i )", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading data" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
//NSLog(#"didStartElement");
// NSLog(#"elementName : %#",elementName);
// NSLog(#"namespaceURI : %#",namespaceURI);
// NSLog(#"qualifiedName : %#",qualifiedName);
NSLog(#"attributeDict : %#",attributeDict);
[registerNewArr addObject:attributeDict];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
////NSLog(#"foundCharacters");
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
////NSLog(#"didEndElement");
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
if ([[[registerNewArr objectAtIndex:1]objectForKey:#"Transaction"]isEqualToString:#"loginxml"])
{
[(WakeuuupLoginScreenVC *)obj getRegisterResult:registerNewArr];
}
}
- (void)dealloc
{
[registerNewArr release];
[super dealloc];
}