在Objective C中将数据发送到服务器

时间:2014-11-02 23:37:20

标签: php ios objective-c xcode

我目前正在尝试将数据从我的xcode项目发送到我制作的服务器,但是当我运行我的应用程序时,数据似乎没有出现在我的表中。

这很简单,允许用户输入按下按钮时发送的名称和消息。我不知道我做错了什么,有什么建议吗?

这是我的php代码:

<?php

$username = "root";
$database = "testdb";

mysql_connect('localhost', $username);

@mysql_select_db($database) or die ("Unable to find database");

$name = @$_GET["name"];
$message = @$_GET["message"];

$query = "INSERT INTO test VALUES ('', '$name', '$message')";

mysql_query($query) or die (mysql_error("error"));

mysql_close();

?> 

和我的对象代码:

.h

#import <UIKit/UIKit.h>

#define kPostURL @"http://localhost/TESTCONNECT.php" //variable to use whenever
#define kName @"name"
#define kMessage @"message"



@interface FirstViewController : UIViewController{

IBOutlet UITextField *nameText;
IBOutlet UITextView *messageText;

NSURLConnection *postConnection;
}

-(IBAction)post:(id)sender;


@end

的.m

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad {
[super viewDidLoad];

}




-(void) postMessage:(NSString*) message withName:(NSString *) name{

if(name !=nil && message !=nil){

    NSMutableString *postString = [NSMutableString stringWithString:kPostURL];
    [postString appendString:[NSString stringWithFormat:@"?%@=%@", kName, name]];

    [postString appendString: [NSString stringWithFormat:@"&%@=%@", kMessage, message]];

    [postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: postString]];


    [request setHTTPMethod:@"POST"];

    postConnection =[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];


}
}

-(IBAction)post:(id)sender{
[self postMessage:messageText.text withName:nameText.text];
[messageText resignFirstResponder];
messageText.text=nil;
nameText.text=nil;

}




- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];

}

@end

2 个答案:

答案 0 :(得分:0)

你在目标C中发帖子,所以在PHP中你需要用$ _POST而不是$ _GET来捕捉变量。

答案 1 :(得分:0)

这就是你如何将字符串发送到php(POST)文件。我认为剩下的应该有效。我没试过,但它看起来不错。

- (void) send {
    NSString *testString = @"this is a test";

    NSString *post =[NSString stringWithFormat:@"message=%@",testString];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"YOUR/URL/test.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
}