0

我正在使用 php 文件从 mysql 获取数据到 iPhone 应用程序,以说明我在 php 中使用此代码的意思

<?php

$host = "localhost";
$user_name = "user_name";
$password = "password";
$db_name = "db_name";
$con = mysql_connect($host,$user_name,$password)or die (mysql_error());
mysql_select_db($db_name)or die (mysql_error());
mysql_query("set names utf8");

$SQL= "SELECT * FROM emails WHERE 1";

$RS = mysql_query($SQL) or die(mysql_error());
mysql_query("set character_set_server='utf8'");

while($row=mysql_fetch_assoc($RS))
$output[]=$row;

    $json_encode =json_encode($output);
    $utf8_decode = utf8_decode($json_encode);
    echo $json_encode;
    mb_convert_encoding($json_encode, 'UTF-8');
    $html_entity_decode = html_entity_decode($json_encode);

?>

在 iPhone 中,我使用了以下代码:

NSString *phpUrl = @"url of my php file";

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

NSArray *statuses = [parser objectWithString:json_string error:nil];

for (NSDictionary *status in statuses)
{
    NSString *sEmailID = [status objectForKey:@"ID"];
    NSString *sEmail = [status objectForKey:@"Email"];
    NSString *sPassword = [status objectForKey:@"Password"];
    NSString *sSMTP = [status objectForKey:@"SMTP"];
}

这对我来说没问题,我得到了我的数据。我也在我的应用程序中多次使用这种方式。但我的问题是请求和响应导致我的应用程序的速度降低并使其运行缓慢。是否有任何方法可以降低请求和响应的速度,或者是否有其他替代方法?提前致谢。

4

1 回答 1

0

问题是您正在发送一个同步请求,这将阻塞您的线程,直到请求完成。一般来说,不建议这样做,也是因为您无法正确处理错误。您应该改为执行异步请求。像这样的东西:

NSString *phpUrl = @"url of my php file";

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error != nil) {
        NSLog(@"%@", error);
        return;
    }

    NSString *json_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSArray *statuses = [parser objectWithString:json_string error:nil];

    for (NSDictionary *status in statuses)
    {
        NSString *sEmailID = [status objectForKey:@"ID"];
        NSString *sEmail = [status objectForKey:@"Email"];
        NSString *sPassword = [status objectForKey:@"Password"];
        NSString *sSMTP = [status objectForKey:@"SMTP"];
    }
}];

RTM了解更多详情。

于 2012-11-16T17:08:46.757 回答