POST method in objective-C and PHP
I have created the following POST method via objective-C
-(IBAction) postLocation: (id) sender{
NSString *latitude = @"37.3229978";
NSString *longitude = @"-122.0321823";
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mydomain.me/webservice.php"]];
[request setHTTPMethod:@"POST"];
NSString *post =[[NSString alloc] initWithFormat:@"latitude=%@longitude=%@submit",latitude,longitude];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningR开发者_如何学JAVAesponse:&response error:&err];
}
and my PHP code is:
if (isset($_POST['submit']){
//it doesn't get into this if statement
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
}
The question is, why can't the PHP code get into the if statement? Where can I state the 'submit' through objective-C?
Your query string for the POST
does not contain the submit
key. You should change it to the following
NSString *post =[[NSString alloc] initWithFormat:@"latitude=%@&longitude=%@&submit=",latitude,longitude];
No "&"s between the parameters.
-(IBAction) postLocation: (id) sender{
NSString *latitude = @"37.3229978";
NSString *longitude = @"-122.0321823";
NSString *post = [NSString stringWithFormat:@"&latitude=%@&longitude=%@", latitude, longitude];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *address_url = @"http://www.mydomain.me/webservice.php?";
address_url = [address stringByAppendingString:post];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:address]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
}
Probably, it is simpler to use if($_SERVER['REQUEST_METHOD'] == 'POST')
instead of the code that you have now to check for form post.
精彩评论