Objective-C and ASIHTTPRequest - response string problems - iphone

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];
}

Related

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.

ASIHTTPRequest only works when i hardcode the strings

I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.
Code that works. Server returns a 200 responce code.
//NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",monograph.uri];
NSURL *url = [NSURL URLWithString:#"http://www.server.com/api/monograph/com/3894.json"];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:appDelegate.key];
[request setPassword:appDelegate.secret];
[request setDelegate:self];
[request startAsynchronous];
Code that fails. Server returns 204 response code for this:
NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",monograph.uri];
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:appDelegate.key];
[request setPassword:appDelegate.secret];
[request setDelegate:self];
[request startAsynchronous];
When i NSLog urlStr it contains:
http://www.server.com/api/monograph/com/3894.json
What am i missing? There must be something to explain it -.-
Regards,
Code
EDIT
checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.
Have you checked whether the NSURL object you get from the string variable is not nil? That could help you home in on the location of the problem.
Also, you might try escaping the string variable, just incase something funny is getting in with the stringWithFormat call.
Cut all the new lines/spaces from the string, this is one possible reason. And sometimes the log doesn't show you the new lines.
try
NSString * s = [monograph.uri stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",s];

ASIHTTPRequest time out

Hello
I am sending some values to the server using ASIHTTPRequest. All works fine until yesterday that the requestFinished didnt work. (when the app send the request on the server an activity indicator and a new view added to the main view and when the request finished is removing the views). I added requestFailed to test if is failed and I get this error:
[3438:207] Error Domain=ASIHTTPRequestErrorDomain Code=2 "The request timed out" UserInfo=0x5ad25c0
Its weird because the same code was working fine yesterday. I am sure that they didnt make any changes on the server's side.
this is the code:
- (IBAction)convert:(id)sender{
//Get the email from the textfield
NSString *email1 = email.text;
//Save the last used email to load it on the next app launch
[[NSUserDefaults standardUserDefaults] setValue:email1 forKey:#"email"];
//Get the current URL from webview
NSString *currentURL= webView.request.URL.relativeString;
lbl.text = currentURL;
//Count the length of Label
int strL= [lbl.text length];
//The url that the requests will be send.
NSURL *url = [NSURL URLWithString:#"the website"];
//Indicator and its view are loading on the screen
[ind startAnimating];
[self.view addSubview:indView];
//ASIHTTPRequests
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *watch = [lbl.text substringWithRange:NSMakeRange(23,strL-23)];
NSString *link = [NSString stringWithFormat:#"http://youtube.com/%#",watch];
[request setShouldRedirect:YES];
[request setPostValue:watch forKey:#"url"];
[request setPostValue:email1 forKey:#"email"];
[request setPostValue:format forKey:#"format"];
[request setPostValue:quality forKey:#"quality"];
[request setDelegate:self];
[request startAsynchronous];
NSLog(#"%# %# %# %#",watch,email1,format,quality);
click=NO;
}
and this is the requestFinished:
- (void)requestFinished:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
NSLog(#"%#",responseString);
NSLog(#"%#",lbl.text);
NSLog(#"requested finished");
[ind stopAnimating];
[indView removeFromSuperview];
[setView removeFromSuperview];
}
Did you try to increase the timeout value on the request? By default it is 10 seconds, you can make it larger by doing this right before the startAsynchronous call:
[request setTimeOutSeconds:60];

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.

iPhone API for Accessing Amazon S3 REST API

Does anyone have any suggestions for GETing from or POSTing to Amazon S3 services using their REST API via the iPhone. It does not look like it is possible but I may be reading the docs wrong.
Thank you in advance for your help!
L.
In a general case I'd recommend to use ASIHttpRequest, it has a lot of built-in functionality (REST compatible too) and a lot of things, making life easier than with NSURLConnection.
It also has S3 support out of box.
You should be able to use the NSURLRequest stuff to do what you want.
NSMutableData* _data = nil;
- (IBAction) doIt:(id)sender {
NSURL* url = [NSURL URLWithString: #"http://theurl.com/"];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
NSURLConnection* con = [NSURLConnection connectionWithRequest: req delegate: self];
NSData* body = [#"body of request" dataUsingEncoding: NSUTF8StringEncoding];
_data = [NSMutableData new];
[req setHTTPMethod: #"POST"];
[req setHTTPBody: body];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_data appendData: data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* result = [[[NSString alloc] initWithData: _data encoding: NSUTF8StringEncoding] autorelease];
// process your result here
NSLog(#"got result: %#", result);
}
This doesn't have any error checking in it and the _data variable should be stored in an instance variable, but the general idea should work for you. You will probably also need to set some request headers to tell the server what encoding the body data is in and so on.