I have an outdated application which use to download an XML document and parse it on the iPhone app, I used the NSURLConnection for that purpose:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//NSLog(#"Response :%#",response);
responseData = [[NSMutableString alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *str = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
[responseData appendString:str];
[str release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DATA : %#",responseData);
if (responseData != nil) {
[self startParsing:responseData];//Parse the data
[responseData release];
}
}
Since moving to use NSXMLParserDelegate with AFXMLRequestOperation, I cannot figure out a way to get xml data properly:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
[responseData appendString:elementName];
[responseData appendString:namespaceURI];
[responseData appendString:qName];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[responseData appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
[responseData appendString:elementName];
[responseData appendString:namespaceURI];
[responseData appendString:qName];
}
-(void) parserDidEndDocument:(NSXMLParser *)parser{
[SVProgressHUD showSuccessWithStatus:#"Downloading completed"];
NSLog(#"DATA : %#",responseData);//not properly appended, tags delimeters are missing
if (responseData != nil) {
[self startParsing:responseData];
[responseData release];
}
}
How to append all the data received from the server in the responseData mutable string ? I debugged the data received after finishing downloading and the xml is missing tags delimeters <>. I think I ma missing the way to get the xml data.
P.S: Please note it's important that I get the xml in a NSMutableString object.
#Fermi
I used AFURLConnectionOperation as you recommended, it works fine with my purpose, but I noticed that my received data is not catched by the delegate methods, instead I can get the data in a completion block:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:API_URL]];
AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];
operation.completionBlock = ^{
NSLog(#"Complete: %#",operation.responseString);//responseString is my data
};
[operation start];
[SVProgressHUD showWithStatus:#"Downloading files"];
wo since NSURLConnection delegate methods are not called, how can I manage failure, etc? Thanx.
AFXMLRequestOperation is explicitly intended to be used to return you an NSXMLDocument instance, NOT a raw XML string.
If you want the XML string use AFURLConnectionOperation and build the NSMutableString the same way you do with NSURLConnection.
Related
I need to get XML data from this particular address (https://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.xml). But when I run the application, nothing happens. Also honestly I do not know how to get from the above xml id 1, id 2 and so on. I'll be happy for any of your advice. Thx
- (id)initWithArray: (NSMutableArray *)slovoArray {
self = [super init];
if (self) {
self.slovoArray = slovoArray;
}
return self;
}
- (void)parseXMLFile
{
NSURL *url = [[NSURL alloc] initWithString:#"https://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.xml"];
self.parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
self.parser.delegate = self;
[self.parser parse];
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
self.element = elementName;
if ([_element isEqualToString:#"radek"]) {
_item = [[NSMutableDictionary alloc] init];
self.kod = [[NSMutableString alloc] init];
self.kurz = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([self.element isEqualToString:#"kod"])
{
[self.kod appendString:string];
}
else if ([self.element isEqualToString:#"kurz"])
{
[self.kurz appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"radek"]) {
Slova *thisSlovo = [[Slova alloc] initWithName:self.kod
kurz:self.kurz];
[self.slovoArray addObject:thisSlovo];
}
self.element = nil;
}
#end
Try this
NSURL *url = [NSURL URLWithString: #"Enter Here your webservice url" ];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * rsltStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:rsltStr error:&parseError]; // In this I have used XMLReader file
Download XML Reader file from here : - XML Reader Download
For more help about XMLReader Visit here :- SOAP webservice calling in iOS with xml parsing
To read XML data from URLs, I recently wrote a simple XML parser for iOS called ConiferXML that might do what you're looking for. You can check it out at GitHub. If this doesn't work out there is also another library on GitHub that is a little more complex but does the same thing.
I am facing a problem in parsing data from a web service response.
I call a web service and get the response as NSLog, but I need to capture the data as NSString.
Here is my sample code:
-(void)connection:(NSURLConnection *) connection didReceiveResponse: (NSURLResponse *) response {
}
-(void)connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
NSString *strData;
strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
[xmlParser setDelegate:self];
[xmlParser parse];
soapResultsString=[[NSMutableString alloc]init];
recordResults =YES;
}
NSString *xmlparserString;
NSMutableString *soapResultsString;
bool recordResults;
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict
{
xmlparserString=elementName;
if( [xmlparserString isEqualToString:#"ns:return"])
{
recordResults =YES;
soapResultsString = [[NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if( recordResults )
{
[soapResultsString appendString: string];
NSLog(#"inside%#",string);
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if( [elementName isEqualToString:#"ns:return"])
{
NSLog(#"parser==>%#",parser);
NSLog(#"nameSpaceUrL==>%#",namespaceURI);
NSLog(#"qName==>%#",qName);
NSData *data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// NSLog(#"json==>%#",json);
NSArray *planArray = [json objectForKey:#"hello_History"];
NSLog(#"planArrayCount==>%lu",(unsigned long)[planArray count]);
NSMutableArray *dataSource = [NSMutableArray arrayWithCapacity:planArray.count];
for (int i = 0 ; i<[planArray count]; i++)
{
recordResults = NO;
txn_id=[[[json valueForKey:#"hello_History"]valueForKey:#"date"]objectAtIndex:i];
loginId = [[[json valueForKey:#"hello_History"]valueForKey:#"time"]objectAtIndex:i];
}
}
}
the problem is i getting outputupto this method
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
but my parsing method not at called
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
is there any alternate way to capture the string
I'm working on an app where user sends data to a central database using a web service. The web service sends back an XML file with the primary key from the central database so the local database on the app is updated with this primary key. When I don't use GCD, everything works perfectly. As soon as I introduce threading, I don't seem to get the XML file to parse. It seems like the code sends the XML to the web service, but nothing happens thereafter. Is there something wrong with the way i implement threading? Here's the code sample:
-(void) viewDidLoad
{
dispatch_queue_t saveCentralDB = dispatch_queue_create("Writing Database", NULL);
dispatch_async(saveCentralDB, ^ {
NSLog(#"Created NEW THREAD to send info to CENTRAL DB");
NSString *soapMsg = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap12:Envelope "
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
"xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
"<soap12:Body>"
"<InsertPurchase xmlns=\"http://tempuri.org/\">"
"<RequestObject xsi:type = \"SpazaPurchaseRequest\">"
"<PurchaseID>%#</PurchaseID>"
"<RemoteSpazaPurchaseID>%#</RemoteSpazaPurchaseID>"
"<UserID>%d</UserID>"
"<RetailerID>%#</RetailerID>"
"<ItemID>%#</ItemID>"
"<CostPrice>%#</CostPrice>"
"<Longitude>%#</Longitude>"
"<Latitude>%#</Latitude>"
"<DatePurchased>%#</DatePurchased>"
"<Barcode>%#</Barcode>"
"<BasketID>%#</BasketID>"
"</RequestObject>"
"</InsertPurchase>"
"</soap12:Body>"
"</soap12:Envelope>",#"0",pklPurchaseID1,fklUserID,fklRetailerID1,fklItemID1, lCostPrice1, sLongitude1, sLatitude1,dtPurchase1,sBarcode1,fklBasketID1];
//---print of the XML to examine---
NSLog(#"%#", soapMsg);
NSURL *url = [NSURL URLWithString:#"http://www.myapp.com/purchases/ProviderWS.asmx?op=InsertPurchase"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [NSMutableData data];
}
});
}
I then implement the following methods to deal with the response from the Web Service.
/************************Processing the feedback XML returned by webservice*****************/
-(void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *) response{
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection
didReceiveData:(NSData *) data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection
didFailWithError:(NSError *) error {
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---prints the XML received---
NSLog(#"%#", theXML);
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
}
The normal delegate methods are then implemented:
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"XML Parsing Method: didStartElement");
//This is the first node that we search for. The information we want is contained within this node.
if ([elementname isEqualToString:#"ResponseMessage"])
{
currentCentralDBPurchase = [parsingCentralDBPurchaseXML alloc];
//Flag to indicate that we are within the ResponseMessage node/tag.
isStatus = YES;
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"XML Parsing Method: foundCharacters");
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (isStatus)
{
if ([elementname isEqualToString:#"PurchaseID"])
{
currentCentralDBPurchase.centralPurchaseID = currentNodeContent;
}
if ([elementname isEqualToString:#"RemotePurchaseID"])
{
currentCentralDBPurchase.localPurchaseID = currentNodeContent;
}
}
if ([elementname isEqualToString:#"ResponseMessage"])
{
//Update local database with the PurchaseID from the central database. This is how we will identify records that must still be sent to the central database.
//Now update the local database with purchases that have been sent to central database
// Get the DBAccess object;
DBAccess *dbAccess = [[DBAccess alloc] init];
[dbAccess UpdateCentralPurchaseID: [currentCentralDBPurchase.localPurchaseID integerValue] :[currentCentralDBPurchase.centralPurchaseID integerValue] ];
// Close the database because we are finished with it
[dbAccess closeDatabase];
currentCentralDBPurchase = nil;
//Clear the currentNodeContent node so we are ready to process the next one.
currentNodeContent = nil;
}
}
NSURLConnection initWithRequest: should be called on the main thread in this situation.
dispatch_async(dispatch_get_main_queue(), ^{
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [NSMutableData data];
}
});
It relies on RunLoop and Runloop is automatically working on the main thread. You can call initWithRequest on the other thread but you should execute RunLoop on the thread. However it is kind of difficult on a dispatch queue, thus using the main queue is helpful for the situation.
I use a webservice to take information. When I take string result, I can not write it into an array.
In foundCharacters when I write NSLog(#"%#",string); it writes all values correctly but when I write:
[myArray addObject:string];
NSLog(#"%#",myArray);
I see lots of nulls. How can I take these values and write them into an array :(
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[datawebservice setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[datawebservice appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
xmlparserr = [[NSXMLParser alloc] initWithData:datawebservice];
[xmlparserr setDelegate:self];
[xmlparserr parse];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
elementyedek = elementName;
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([elementyedek isEqualToString:#"StokAdi"]) {
[myArray addObject:string];
NSLog(#"%#",myArray);
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConnection");
}
I'm writing an App that is parsing Data from an XML-Doc on the web. So when it finishes loading it is supposed to call the Parsing Method as follows.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self startParsingData];
}
This should work in theory, right? Problem is I'm getting this error:
Reciever type 'ffwDetailViewController' for instance message does not declare a method with selector 'startParsing Data'
I take it, that xCode thinks this method doesn't exist., but it does.
-(void)startParsingData{
NSXMLParser *dataParser = [[NSXMLParser alloc] initWithData:recievedData];
dataParser.delegate = self;
[dataParser parse];
}
I don't know what to do. I would really appreciate any help.
Switching their Position did the trick. Unfortunately, now the app crashes on pressing the Button. Here's the full code. I hope you can help me.
- (IBAction)getMissions:(id)sender {
if (recievedData) {
recievedData = nil;
}
_einsaetze.text=#"Pasing Data...";
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://oliverengelhardt.de/ffw_app/test.xml"]]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//Start loading Data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
recievedData = [NSMutableData data];
}else{
[_einsaetze setText:#"connection failed"];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[recievedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if (recievedData) {
[recievedData appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
_einsaetze.text=#"connnection failed";
}
-(void)startParsingData{
NSXMLParser *dataParser = [[NSXMLParser alloc] initWithData:recievedData];
dataParser.delegate = self;
[dataParser parse];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self startParsingData];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:#"element"]) {
NSString *myData = [NSString stringWithFormat:#"%#", [attributeDict objectForKey:#"myData"]];
_einsaetze.text = myData;
}
}
If -(void)startParsingData is not declared in the #interface section of the class (either in the .h or in an extension in the .m file) then -(void)startParsingData needs to be physically before -(void)connectionDidFinishLoading in the .m file.
What order are they in your .m file?