我試着在用戶在字段(標題,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