[英]How To Send “chat message” From iOS TextField To A Remote Database
因此,我嘗試創建一個簡單的iOS程序,在其中可以將聊天消息保存到遠程MySQL服務器,然后將其加載回。
我的應用程序具有可在其中輸入數據的文本框和一個將數據保存到外部數據庫的按鈕。
我的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
現在,我已將其編碼為僅存儲名稱。
我想存儲一個聊天消息,例如“你好,你好嗎?”,因此該字符串無法正確存儲到外部服務器。 知道我該如何實現嗎? 謝謝。
您不應使用dataWithContentsOfURL。 那是阻塞電話。 它將凍結UI,直到網絡請求完成。 您想使用NSURLConnection進行HTTP獲取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.