php - 如何将变量作为 POST 从 Cocoa-Touch 应用程序发送到我的 php 站点?

标签 php ios cocoa-touch post nsmutableurlrequest

我有一个 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];

而不是您现在使用的代码。

来源:

http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

编辑 不要忘记在失败和成功时释放 NSURLConnection 对象(其中一个对象只被调用一次),否则会泄漏。如果您使用 ARC,请将其保存在 ivar 中,否则它可能会在启动后立即被释放(需要对此进行确认)

关于php - 如何将变量作为 POST 从 Cocoa-Touch 应用程序发送到我的 php 站点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549537/

相关文章:

php - 基于国家的重定向

iphone - UIActivityViewController 有错误的按钮标题颜色

objective-c - UISearchDisplayController 显示白色而不是灰色表格单元格边框

objective-c - 知道 textField :shouldChangeCharactersInRange:replacementString: 中完整更改的字符串

ios - 如何四舍五入 NSNumber 并在对象 C 中创建一系列数字

objective-c - 在 Cocoa Touch 中从字符串中删除空格的最佳方法是什么?

php - 写时复制会防止阵列上的数据重复吗?

php - 如何在 PHP 中验证电子邮件?

php - 使用代理和通过代理建立隧道有什么区别

ios - dispatch_async 中的同步块(synchronized block)