在Objective-c中POSTING后从PHP获取结果

时间:2012-12-17 22:24:21

标签: objective-c

我正在尝试学习如何使用PHP和Objective-c来使用POST和GET。

我遇到了一个问题。在使用objective-c进行POST后,如何获得返回结果?

我的PHP文件是:

<html>
<head><title>Bug Reporter</title></head>
<body>
<h2>Fancy Bug Reporter</h2>
<hr />
<?php
if (isset($_POST['go']))
{
        // Form was posted
        print "User submitted bug: ". $_POST['name'] . ": " . $_POST['description'];
}
else
{
        // Form was not posted, display form
?>
<form method="POST" action="<?php echo $PHP_SELF; ?>">
Bug Name:<br /><input type="text" name="name" maxlength="100" /><br />
Bug Description:<br /><input type="text" name="description" maxlength="1000" size="80" /><br />
<input type="submit" name="go" value="Add Bug">
</form>
<?php
}
?>
</body>
</html>

在objective-c:

    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:
     [NSURL URLWithString:@"http://xxxxx.com/xxx.php"]];

    [request setHTTPMethod:@"POST"];

    NSString *postString = @"go=1&name=Bad%20Bad%20Bug&description=This%20bug%20is%20really%20really%20super%20bad.";

    [request setValue:[NSString
                       stringWithFormat:@"%d", [postString length]]
   forHTTPHeaderField:@"Content-length"];

    [request setHTTPBody:[postString
                          dataUsingEncoding:NSUTF8StringEncoding]];


    [[NSURLConnection alloc]
     initWithRequest:request delegate:self];

2 个答案:

答案 0 :(得分:1)

您需要实现NSURLConnectionDelegate方法,这些方法将针对与您的请求相关的任何网络连接事件进行调用,例如身份验证,失败,成功,收到的数据等。

另外,我建议你看看AFNetworking,这是一个很棒的网络库,它包含NSURLConnection提供基于块的方法。

如果发现它比普通NSURLConnection方式更方便。

答案 1 :(得分:0)

您永远不会保存连接而无法启动它。 使用新的便利方法:

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*r, NSData*d, NSError*e) { 
     ...
 }