2014-11-22 42 views
0

所以我试图创建一个简单的iOS程序,我可以将聊天消息保存到远程MySQL服务器,然后加载它。如何发送“聊天消息”从iOS TextField到远程数据库

我的应用程序有文本框,我可以输入数据和一个按钮将数据保存到外部数据库。

我的PHP文件看起来像这样:

<?php 

$DB_HostName = "hostname"; 
$DB_Name = "dbname"; 
$DB_User = "dbuser"; 
$DB_Pass = "dbpass"; 
$DB_Table = "dbtable"; 

if (isset ($_GET["name"])) 
    $name = $_GET["name"]; 
else 
    //$name = "Ghalia"; 
    echo ('Please enter a name'); 

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
mysql_select_db($DB_Name,$con) or die(mysql_error()); 

$sql = "insert into $DB_Table (name) values('$name');"; 
$res = mysql_query($sql,$con) or die(mysql_error()); 

mysql_close($con); 
if ($res) { 
    echo "success"; 
}else{ 
    echo "faild"; 
} 
?> 

我ViewController.h文件看起来像这样:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize txtName; 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

- (IBAction)insert:(id)sender { 
//create string contains url address for php file, the file name is phpfile.php, it receives a  parameter :name 

NSString *strURL = [NSString stringWithFormat:@"http://xxdsadxx.net/phpFile.php?name=%@", txtName.text]; 

//to execute php code 
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; 
//to receive the returned value 
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]; 

NSLog(@"%@", strResult); 

} 
@end 

现在,我把它编码为唯一商店名称。

我想存储像“你好,你好吗?”的聊天消息,该字符串将不会正确存储到外部服务器。任何想法如何我可以实现这一目标?谢谢。

+0

您是说发送名称的代码无法正常工作,并且您希望在继续发送聊天文本之前完成这项工作? – 2014-11-22 22:13:54

+0

此代码适用于名称输入。但我想让它识别多个字符串,例如“你好吗?”。我怎么做? – 2014-11-23 21:25:27

回答

0

您不应该使用dataWithContentsOfURL。这是一个阻塞呼叫。它会冻结用户界面直到网络请求完成。你想用NSURLConnection做一个HTTP获取。

相关问题