Encoding on NSURLConnection - iphone

I need to load data from a REST service, but the result is always (null) when I have any accentuation. I know this is an encoding problem but NSUrlConnection gives me no solution. The best result I got is to have all my text with strange codes in the place of the accentuated characters.
I already tried to use NSUrl like the following code and it works, but I need to set two headers for this connection.
NSURL *nsurl = [[NSURL alloc] initWithString:url];
NSString *data = [[NSString alloc] initWithContentsOfURL:nsurl encoding: NSUTF8StringEncoding error: nil];
Well I could have two solutions for this taks, adding headers do NSUrl connection or manage to make the encoding to work in NSURLConnection.
Does anyone have a solution?

You can add header fields for your request in an NSMutableURLRequest instance with setValue:forHTTPHeaderField:

Related

NSUrlRequest itself adding %0 in url

The NSURLRequest is adding %0 in request. I created the string and converted it into base 64 then send to url, but NSURLRequest is automatically adding %0 in it. Below is the code i am using.
This is how converted to base 64.
NSData *plainTextData = [totalStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
NSLog(#"encoded url:%#",base64String);
When Api called.
NSString *urlStr = [NSString stringWithFormat:#"http://mabct.co/api/checkin/%#", [code valueForKey:#"code"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:urlStr]];
// [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSString *responseString = [MyEventApi sendRequest:request];
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"dict in API-------------%#",results);
return results;
This is the converted string in to base 64
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0yMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what NSURLRequest is sending.
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0y%0D%0AMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what i am sending in encoding
"{"eventId":"47","seat":"10_Karan Makhija_24-04-2013 10:06","userId":"10"}"
I am not getting what is wrong, please guide for the above.
Thanks in advance.
I see that %0D%0A is being added to your original string. I googled it and found that:
%0D%0A is the encoded ASCII non-printable characters of ,
which on Microsoft platforms is a NewLine So:
Consider if you accidentally could have replaced some HTML by hitting the return key while editing your files.
2a. Be aware of what
encoding your editor uses for saving the files (typically either
ASCII, ANSI, or Unicode)
2b. Your webserver (an IIS6, likely running
on a Windows 2003 Server) serves the files as UTF-8 encoded, which is
fine - But you may want to verify that it actually reads the files
using same encoding as you've used for saving the files.
Here, is the SOURCE if you want to check.
EDIT
Make sure that your webserver and client uses the same encoding (i.e. NSUTF8StringEncoding or any other, but same)
Also, IF base 64 encoding is there on web server. Follow this link, for implementing category for such encoding/decoding. I hope this will help you.

NSMutableURLRequest sends partial post body

I'm sending a base64 encoded image to a server as part of a post request using NSMutableURLRequest. What I log as the post body and what the server receives are not the same thing. The server seems to get a truncated version, as though the connection aborts midway. See the code below:
NSString *dataStr = [NSString stringWithFormat:#"request_data=%#",reqStr];
NSLog(#"datastr is %#",dataStr);
NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"nsdata length is: %i",[dataForUrl length]);
[urlRequest setHTTPBody:dataForUrl];
[urlRequest setValue:[NSString stringWithFormat:#"%d", [dataForUrl length]] forHTTPHeaderField:#"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *res, NSData *data, NSError *err) {
// ...
}
The first log statement shows the correct data. I even took the base64 part of the string to http://www.motobit.com/util/base64-decoder-encoder.asp, decoded it as a jpg, and it is the correct image. The second log statement shows that the length is the right size (422624 when the picture was 422480, for example).
I can't find anything wrong with the connection details or the data. The phone makes the connection, sends some data, then either the phone stops sending or the server stops receiving. What could cause that?
Edit: link to sample data http://pastebin.com/BS9HjKhg
Edit2: The server or iOS is converting the +'s from the image to spaces. I'll post an answer when I figure out the right way to send it.
I was able to compare a full sample from the server vs what xcode logged, and found the + converted to [space]. Since that was the only character having a problem and url encoding is buggy in iOS, I just did
NSString *dataStr = [NSString stringWithFormat:#"request_data=%#",[reqStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"]];
The server is accepting them again. I'm still not sure whether the server was the problem or it was iOS. The other OS's that connect use the same application/x-www-form-urlencoded as their content type with no problems.
I would suggest doing the conversion from Base64 string into NSData through Nick Lockwood's Base64 class.
That
NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
worries me a bit (even more after looking at how Base64 is implements the conversion)...

GET http requests In Objective C

I have the following code in objective c that is supposed to make a GET http request to my website which in turn will submit something into my MySQL database...
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.website.com/VideoPush/plist/urlTransfer.php"]];
[request setHTTPMethod:#"GET"];
NSString *post =[[NSString alloc] initWithFormat:#"videoID=%#",videoURL];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
Note: I'm a total beginner to http requests with Objective c so I realize I could be missing something obvious...
Now if I run the following url in my browser...
http://www.website.com/VideoPush/plist/urlTransfer.php?videoID=hhklskdjsad
Then something gets entered into the database, but not when I'm using objective c. Also what is the difference between GET and POST when you make requests like this (since the user doesn't see the url anyways)?
ALSO: Am I allowed to pass a url (still a nsstring with /'s though) as the videoURL variable above
You've tried to set the body of a GET request, which makes no sense. What you probably want is:
NSString *urlString = [NSString stringWithFormat:#"http://www.website.com/VideoPush/plist/urlTransfer.php?videoID=%#", videoURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
... the rest of your method ...
You should probably go and have a read up about what a GET and a POST is and why I said it makes no sense to have a body in a GET request.
ALSO: Am I allowed to pass a url (still a nsstring with /'s though) as the videoURL variable above
No, you will need to URL encode anything in the query string. You can use CFURLCreateStringByAddingPercentEscapes to do this for you.

How to upload NSData Object to server with specific name?

How to upload NSData Object to server with specific name ?
NSData *imgData; // Image Data
NSString *imgName = #"myfile.png";
I want to upload data to server with specific file name.
1. Upload Data (imgData)
2. To server (my_server.com/upload.html)
3. With file name (imgName)
I am currently working on a school project where I needed to do something similar to this...
I was placing longitude and latitude values in a database.
MAKE NOTE THAT THERE MAY BE MUCH SIMPLER WAYS TO DO THIS. I AM BY NO MEANS A "PRO" AT OBJECTIVE-C PROGRAMMING
There are going to be three things you need.
a server in which you have access to.
a PHP file that will write the data to the database.
an NSURLConnection object;
I had placed the following code in one of the delegate methods for CLLocationManager.
The NSURLConnection object should look something like this:
//this is where I put the url for my PHP file
url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://www.example.com/folder/example.php"]];
urlRequest = [NSURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
Of course the variables: url, urlRequest, and connection are declared in the header file like this
NSURL *url;
NSURLRequest *urlRequest;
NSMutableData *filedata;
NSURLConnection *connection;

iPhone NSURLConnection: What to do with returned NSData Object? Google Docs API

I'm working with the Google Docs API in my iPhone application. I've sent the proper POST request, and received a response along with some NSData. If I NSLog the NSData object, I get this:
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:theResponse error:NULL];
NSLog(#"%#",returnedData);
//output : <4572726f 723d4261 64417574 68656e74 69636174 696f6e0a>
I think the NSData is either an NSDictionary or an NSArray. I'm supposed to receive a couple of items back, an SID, an LSID, and an Auth.
If I could turn the NSData chunk into an NSDictionary I could just find the object for whichever key.
Can anyone help?
You will have to decode the data. Try the following:
NSString *result= [[NSString alloc] initWithData:returnedData encoding:NSASCIIStringEncoding];
Of course this will depend on how the data is encoded. NSUTF8StringEncoding might work instead.
You may just need to pass the data to an NSXMLParser
The best way to deal with web data is Doing NSXML parsing. No need of decoding data the parser will handle itself