我试着在用户在字段(标题,desc,城市)中输入数据后执行以下代码,然后单击保存。从iOS发布数据到PHP脚本
- (IBAction)saveDataAction:(id)sender {
NSString *lEventTitle = [NSString stringWithFormat:@"var=%@",eventTitle.text];
NSString *lEventDesc = [NSString stringWithFormat:@"var=%@",eventDescription.text];
NSString *lEventCity = [NSString stringWithFormat:@"var=%@",eventCity.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mydomain.com/ios/form.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
//this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send
NSString *postString = [[NSString alloc] initWithFormat:@"title=%@&description=%@&city=%@", lEventTitle, lEventDesc, lEventCity];
NSString *clearPost = [postString
stringByReplacingOccurrencesOfString:@"var=" withString:@""];
NSLog(@"%@", clearPost);
[request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:clearPost forHTTPHeaderField:@"Content-Length"];
[NSURLConnection connectionWithRequest:request delegate:self];
NSLog(@"%@", request);
}
当我的NSLog的clearPost串(包含变量串被发送到服务器),它示出了:
title=xmas&description=Celebration&city=NY
在PHP目的,我有简单的为:
<?php
$title = $_POST['title'];
$description = $_POST['description'];
$city = $_POST['city'];
echo "Title: ". $title;
echo "Description: ". $description;
echo "City: ". $city;
?>
只是试图获取PHP的数据,以便以后我可以操纵它。现在,当我执行
domain.com/ios/form.php时,它显示标题,说明和城市为空。
对不起,但我对iOS和Objective-C非常新。
1,什么是问题? 2.为每个POST变量添加'name ='部分两次:在方法的前三行添加一次,然后创建'postString'。 – 2013-03-23 16:44:07
抱歉的问题编辑 – 2013-03-23 16:52:54
IOS 9引入了ATS,并且不会允许正常的HTTP请求没有白名单。信用:(http://stackoverflow.com/a/30732693/6042879) – 2016-07-29 20:21:14