我正在使用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"];
}这对我来说很好,我得到了我的数据。我也在我的应用程序中多次使用这种方式。但我的问题是,请求和响应导致我的应用程序的速度降低,并使其工作得如此缓慢。是否有任何方法可以降低请求和响应的速度,或者是否有任何替代方法来代替这一点?提前谢谢。
发布于 2012-11-17 01:08:47
问题是您正在发送一个同步请求,这将阻塞您的线程,直到请求完成。通常,不建议这样做,这也是因为您无法正确处理错误。您应该改为执行异步请求。如下所示:
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获取更多详细信息。
https://stackoverflow.com/questions/13420829
复制相似问题