2013-03-23 91 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