IPhone POST with PHP Error

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 send data to my PHP server to register the device in our database, but for some of my users POST data is not sent. I was told that this line:

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

may cause a problem. Any thoughts on why this script sometimes doesn't send POST data? On the server, I received a packet trace for unsuccessful sending, and the content length is 0, so no data was sent.

+3
source share
3 answers

I perform a similar function in my own, and the only thing that is different is the line that you think is wrong. Try to do

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

stringByUrlEncoding ( , , atm).

,

+2

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

0

By the way, you can get the application version from the properties:

NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; [request setValue:[NSString stringWithFormat:@"My App %@", appVersion] forHTTPHeaderField:@"User-Agent"];
0
source

Source: https://habr.com/ru/post/1735840/


All Articles