我有一个 iPhone 应用程序,我想将一些表单数据发送到我的网站(用 PHP 编写)。
//This problem has now been solved. Typo in url.. :(
NSString *urlString = "http://www.mywebsite.com/test.php";
NSUrl *url = [NSURLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *variableToSend = [NSString stringWithFormat:@"name=John"];
//I have assumed that where I write "name=John" that "name" is in Php equal
//to $_POST['name']?, and that "John" is the value of it?
[request setHTTPMethod:@"POST"];
//I don't quite understand these..
[request setValue:[NSString stringWithFormat:@"%d", [variableToSend length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[variableToSend dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
我的 php 文件只是 $name = $_POST['name'];并将 $name 写入数据库。 我创建了一个带有 method="post"、action=""的 < form > ,以及一个名为“name”的文本字段,并且成功了。该值已发送到数据库。
我在很多答案中都看到过这个代码示例,但它对我来说确实有用..有些代码行我不理解,所以我相信我设置 php 和 php 的方式有问题代码如何发送变量..有人知道我哪里出错了吗?
(现在这里的代码是手工编写的,所以可能会有拼写错误,但是所有内容都在 xcode 中编译,如果我 NSLog(@"%@", request),我会得到“< NSURLConnection: 0x1d342c24>”或其他内容..不知道这是否正确..)
编辑
我的测试.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$connection = mysql_connect("host","un","pw");
if (!$connection){
die('Error: ' . mysql_error());
}
if(isset($_POST['name']))
{
$name = $_POST['name'];
mysql_select_db("db", $connection);
mysql_query("INSERT INTO tablename(Name)
VALUES ('$name')");
mysql_close($connection);
}
?>
</body>
</html>
斯蒂
最佳答案
我已经意识到你的问题:你的 NSURLConnection 实例永远不会启动(我敢打赌你的 NSURLConnectionDelegate 方法都不会被调用)。
使用:
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
或者只是:
[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
而不是您现在使用的代码。
来源:
编辑 不要忘记在失败和成功时释放 NSURLConnection 对象(其中一个对象只被调用一次),否则会泄漏。如果您使用 ARC,请将其保存在 ivar 中,否则它可能会在启动后立即被释放(需要对此进行确认)
关于php - 如何将变量作为 POST 从 Cocoa-Touch 应用程序发送到我的 php 站点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549537/