iPhone NSString convert to readable text - iphone

I have a piece of NSString that will read "Test & Test" or with "
Is there any way without searching and replacing to make that display as "&" or """ ??

Can you try this ?
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.mypage.com/content.html"]]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse* authResponse;
NSError* authError;
NSData * authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&authResponse error:&authError];
NSString *authResponseBody = [[NSString alloc] initWithData:authData encoding:NSUTF8StringEncoding];
NSLog(#" Nice Result: %#", authResponseBody);
Adrian

CFXMLCreateStringByUnescapingEntities should do it. Thanks to the magic of toll free bridging you can just use your NSString.

The html string you read is bad formated.
Try to read as UTF-8 or any other formatting in order to get the correct text from the html you're reading.
Can you actually post the code where you read the NSString from the HTML content ?

Related

Parsing XML String From WebServer

Alright, so here's where I'm at with my app.
I've got some code that connects to a remote server and grabs some XML data, and forms it into a string. Here is the code below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *accept = [NSString stringWithFormat:#"application/xml"];
[request addValue:accept forHTTPHeaderField: #"Accept"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Which returns
That's exactly the information I want. My question is how I can get the double value out of the gold brackets and into my application to use.
Thanks a lot!
There are a lot of tutorials of how to use NSXMLParser. For example, ray wenderlich or here and here.
There's quite a few XML parsing options available - ranging from libxml2, to NSXMLParser and a host of open-source projects.
One of my favorite XML parsers is RaptureXML, which can be installed via CocoaPods.
I like to create a category on RXMLElement to parse as follows:
- (PFCurrentConditions*)asCurrentCondition
{
NSString* summary = [[self child:#"weatherDesc"] text];
PFTemperature* temp = [PFTemperature temperatureWithFahrenheitString:[[self child:#"temp_F"] text]];
NSString* humidity = [[self child:#"humidity"] text];
NSString* wind =
[NSString stringWithFormat:#"Wind: %# km %#", [[self child:#"windspeedKmph"] text], [[self child:#"winddir16Point"] text]];
NSString* imageUri = [[self child:#"weatherIconUrl"] text];
return [PFCurrentConditions conditionsWithSummary:summary temperature:temp humidity:humidity wind:wind imageUrl:imageUri];
}
So, you can then use it as follows:
RXMLElement* rootElement = [RXMLElement elementFromXMLData:response.responseData];
__autoreleasing PFWeatherReport* weatherReport = [rootElement asWeatherReport];
Again, this is one of countless options, but my personal favorite.

Issue in Image uploading - base64 encoding

I am passing base64 encoded image string to the server side with the HTTP PUT method.I have tried several times but getting error message as response. That error message is because null value is getting in the server side. I have checked the same, in android code and its working fine there. I am attaching my code below.
SBJSON *parser = [[SBJSON alloc] init];
NSString *url=[NSString stringWithFormat:#"The URL i am using"] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"XXXXX" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"PUT"];
NSString *input=[NSString stringWithFormat:#"abc[image]=%#",base64encodedString];
[request setHTTPBody:[input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
[parser release];
[json_string release];
return statuses;
I am getting error message from the server side like this: "xxxxxx.jpg is not recognized by the 'identify' command."
Kindly suggest a solution.
At last i found that the content type should be changed to "multipart/form-data" from "application/x-www-form-urlencoded". Can anyone please tell me how pass Base encoded string using this way? Pls...i am behind this issue for the last 20 days...
There could be a difference in the Base64 routine. Base64 encode the same data on the server and the iPhone and compare.
Using the simulator use a network snooper such as Wireshark on the Mac to see what is really going out and the full return from the server. If you are using SSL you can use the Mac app Charles to see the data.

Iphone dev : how can I get a result from google currency converter?

Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.
I have already tried something like that :
-(IBAction)getResponse:(id) sender{
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil && data != ""){
NSString *response = [[[NSString alloc] initWithData:data]]
[label setText: response];
}
else [label setText:#"not working"];
}
But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract
<div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>
Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR
This URL will return the JSON
{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}
Just parse it. :)
Try...
NSData *data = [[NSData alloc] init];
Then check you've got something in response
NSLog(#"%#", response);
Better yet, remove the NSData alloc/init
Replace with
 
NSData *data=[NSData dataWithContentsOfURL:myURL];
And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
[label setText: responseString];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error]; //you can log the error description
[label setText:#"not working"];
}
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil){
NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSLog(#"%#",response);
}
Try this.
This API is giving HTML responce.

NSURLErrorBadURL error

My iphone app called Google Local Search(non javascript version) to behave some search business.
Below is my code to form a url:
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%#", keyword];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
When the keyword refers to english characters, it works fine, but when refers to chinese characters(encoded in UTF8, such as '天安门' whose UTF8 code is 'e5a4a9 e5ae89 e997a8'), it will report NSURLErrorBadURL error(-1000, Returned when a URL is sufficiently malformed that a URL request cannot be initiated). Why?
Then I carry out further investigation, I use Safari and type in the url below:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=天安门
It also works, and the output I got from Macsniffer is:
/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8
So I write a testing url directly in my app
NSString *url = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=%E5%A4%A9%E5%AE%89%E9%97%A8"];
And what I got from the Macsniffer is some other thing:
/ajax/services/search/local?v=1.0&q=1.687891E-28750X1.417C0001416CP-102640X1.4CC2D04648FBP-9999-1.989891E+0050X1.20DC00184CC67P-953E8E99A8
It seems my keyword "%E5%A4%A9%E5%AE%89%E9%97%A8" was translated into something else. So how can I form a valid url? I do need help!
Have you tried encoding the search string:
NSString* escapedKeyword = [keyword stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

Objective-C and ASIHTTPRequest - response string problems

I'm using the ASIHTTPRequest package to send some data from the iPhone to my server and then when saved on server I recieve a response (a string) containing a url that I want to load in a webview. In theory this should be simple, but in reality I can't get this work at all. Seems to be some problems with encoding of the string I guess. If I NSLog out the response it seems to be totally fine, but it just refuses to load in the webview.
This is my request (been playing around with compression and encoding):
NSURL *url = [NSURL URLWithString:#"xxx"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setFile:imageData forKey:#"photo"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[request setAllowCompressedResponse:NO];
[request setDefaultResponseEncoding:NSUTF8StringEncoding];//NSISOLatin1StringEncoding
[request start];
And this is my responder:
- (void)requestDone:(ASIHTTPRequest *)request{
NSString *response = [request.responseString];
NSLog(#"web content: %#", response);
[webView loadSite:response];
}
The NSLog seems fine, but site just won't load. Tried sending an NSString variable like NSString *temp = #"http://www.google.se"; to the loadSite function and that works fine, so the problem is not with the loading itself.
Would greatly appriciate any pointers or help in the obj-c jungle :)
/f
Try to do the following:
NSString *response = [[request responseString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
It will trim all whitespaces and newlines.
so turns out that a response is automatically ended with a \n (new linebreak). this didn't show up when logging the variable, neither when writing it to a textfield but when converting it to a urlobject and logging that i found it. debugging once again pays off ;)
woups, my responder is of course:
- (void)requestDone:(ASIHTTPRequest *)request{
NSString *response = [request responseString];
NSLog(#"web content: %#", response);
[webView loadSite:response];
}