3

I have this code here:

NSString *post = [NSString stringWithFormat:@"deviceIdentifier=%@&deviceToken=%@",deviceIdentifier,deviceToken]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:@"http://website.com/RegisterScript.php"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"MyApp-V1.0" forHTTPHeaderField:@"User-Agent"];
[request setHTTPBody:postData]; 
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *response = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding]; 

which should be sending data to my PHP server to register the device into our database, but for some of my users no POST data is being sent. I've been told that this line:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

may be causing the problem. Any thoughts on why this script would sometimes not send the POST data? On the server I got the packet trace for a failed send and the Content-lenght came up as 0 so no data was sent at all.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alexander
  • 409
  • 1
  • 4
  • 14

3 Answers3

2

I am doing a similar function in mine and the only thing that differs is the line you think is wrong. Try doing

NSMutableData *postData = [NSMutableData data];
[postData appendData:[[NSString stringWithFormat::@"deviceIdentifier=%@&deviceToken=%@",deviceIdentifier,deviceToken]dataUsingEncoding:NSUTF8StringEncoding]];

stringByUrlEncoding basically replaces any reserved characters with their character encoded safe string(I think thats the best way to explain it, my mind is blank atm).

Hope that helps

Rudiger
  • 6,749
  • 13
  • 51
  • 102
  • Where are you using stringByURLEncoding? I did replace my code with yours above though, seems like its workin! :D – Alexander Mar 08 '10 at 02:58
  • I use it on the variables, sorry I thought I put it in. So yours would be [deviceIdentifier stringByUrlEncoding], [deviceToken stringByUrlEncoding]. http://www.drobnik.com/touch/2009/08/url-encoding/ explains why to use it and the code as well – Rudiger Mar 08 '10 at 03:16
0

Test your data: NSLog([[NSString alloc] initWithData: postData encoding:NSAsciiStringEncoding]);

Andrew
  • 11
  • 1
0

By the way you can get app version from the properties:

NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; [request setValue:[NSString stringWithFormat:@"My App %@", appVersion] forHTTPHeaderField:@"User-Agent"];
dimzzy
  • 247
  • 2
  • 6