2013-03-23 183 views
9

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

+0

1,什麼是問題? 2.爲每個POST變量添加'name ='部分兩次:在方法的前三行添加一次,然後創建'postString'。 – 2013-03-23 16:44:07

+0

抱歉的問題編輯 – 2013-03-23 16:52:54

+0

IOS 9引入了ATS,並且不會允許正常的HTTP請求沒有白名單。信用:(http://stackoverflow.com/a/30732693/6042879) – 2016-07-29 20:21:14

回答

15

目標C

// Create your request string with parameter name as defined in PHP file 
NSString *myRequestString = [NSString stringWithFormat:@"title=%@&description=%@&city=%@",eventTitle.text,eventDescription.text,eventCity.text]; 

// Create Data from request 
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.youardomain.com/phpfilename.php"]]; 
// set Request Type 
[request setHTTPMethod: @"POST"]; 
// Set content-type 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
// Set Request Body 
[request setHTTPBody: myRequestData]; 
// Now send a request and get Response 
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; 
// Log Response 
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",response); 

斯威夫特

// Create your request string with parameter name as defined in PHP file 
var myRequestString: String = "title=\(eventTitle.text!)&description=\(eventDescription.text!)&city=\(eventCity.text!)" 
// Create Data from request 
var myRequestData: NSData = NSData.dataWithBytes(myRequestString.UTF8String(), length: myRequestString.characters.count) 
var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "http://www.youardomain.com/phpfilename.php")!) 
// set Request Type 
request.HTTPMethod = "POST" 
// Set content-type 
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type") 
// Set Request Body 
request.HTTPBody = myRequestData 
// Now send a request and get Response 
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) 
// Log Response 
var response: String = String(bytes: returnData.bytes(), length: returnData.characters.count, encoding: NSUTF8StringEncoding) 
NSLog("%@", response) 
+0

,請隨時提問。謝謝。 – 2013-03-23 17:17:27

+0

它實際上只用了很少的調整!感謝一個很好的伴侶 – 2013-03-23 19:06:10

+0

讓我檢查我的PHP服務器。我將很快回來 – 2013-03-23 19:17:13

0

請試試這個:

[request setValue:[NSString stringWithFormat:@"%d",[clearPost length]] forHTTPHeaderField:@"Content-Length"]; 

確定我加入了我的請求代碼:它可能有助於

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
             initWithURL:[NSURL 
                URLWithString:@"http://www.sth.com/action/verify.php"]]; 

     [request setHTTPMethod:@"POST"]; 
     [request setValue:[NSString stringWithFormat:@"%i",[sent length]] forHTTPHeaderField:@"Content-length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:[sent dataUsingEncoding:NSASCIIStringEncoding]]; 
+0

我編輯並嘗試以下內容:輸入數據後,我按保存。然後我去chrome並訪問domain.com/ios/form.php。仍然沒有顯示。我做對了嗎? – 2013-03-23 16:55:24

+0

如果您仍然無法正確理解,請您填寫Content-Type,而不是內容類型 – meth 2013-03-23 17:01:51

2

自IOS 9.0以來,NSURLConnection已被排除。請使用NSURLSesstion:

-(void) httpPostWithCustomDelegate 
{ 
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; 

NSURL * url = [NSURL URLWithString:@"http://hayageek.com/examples/jquery/ajax-post/ajax-post.php"]; 
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url]; 
NSString * params [email protected]"name=Ravi&loc=India&age=31&submit=true"; 
[urlRequest setHTTPMethod:@"POST"]; 
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest 
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
             NSLog(@"Response:%@ %@\n", response, error); 
             if(error == nil) 
             { 
              NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 
              NSLog(@"Data = %@",text); 
             } 

            }]; 
[dataTask resume]; 

} 

reference