【问题标题】:xcode request data from php/mysql using NSURLConnection使用 NSURLConnection 从 php/mysql 请求 xcode 数据
【发布时间】:2013-04-13 06:44:08
【问题描述】:

我想使用 NSURLConnection 从 PHP/Mysql 请求中获取一个值(可以是 1 或 0),下面是我的 xcode 和 php/mysql 查询代码

谁能帮我将接收到的数据存储在 NSString 而不是 NSMutableData 中? 我之所以要使用 NSURLConnection 是因为它提供了无连接功能

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.20/iqkradio_stream_ip_flag.php"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:20.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    receivedData = [[NSMutableData data] retain];
    NSString *receivedDataString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
}

else
{
    NSLog(@"no connection or Error");
    // Inform the user that the connection failed.
}

Mysql 文件

 <?php
$con = mysql_connect("192.168.0.15","xxxx","xxxxx");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("qkradio", $con);
$result = mysql_query("select address from iqkradio" );
while($row = mysql_fetch_array($result)) {
echo $row['address'];
}
mysql_close($con);
?>

【问题讨论】:

    标签: php mysql xcode nsurlconnection


    【解决方案1】:

    如果是单个字符,为什么不直接使用:

    NSError *error;
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://192.168.0.20/iqkradio_stream_ip_flag.php"] encoding:NSASCIIStringEncoding error:&error];
    

    它比NSURLConnection 容易得多,并且不应该用这么小的有效负载阻塞太多。如果您担心这一点,您可以随时将其包装在 dispatch_async 中。

    【讨论】:

    • 是的,我知道,但是当 url 无法访问时,我的代码会阻塞 60 秒。捕获阻塞的任何其他解决方案
    • 无论如何,您都应该在调用之前检查 URL 的可访问性。这是苹果的要求之一。如果可达性为假,则不要拨打电话。
    • 使用此代码:github.com/tonymillion/Reachability。它将允许您测试连接是否可行。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多