从php到iOS应用程序的json响应不完整
在我的iOS应用程序中,我有一个异步连接,可以调用服务器上的php脚本。该脚本对数据库进行查询,并使用json_encode给出响应 以下是脚本:从php到iOS应用程序的json响应不完整,php,ios,json,Php,Ios,Json,在我的iOS应用程序中,我有一个异步连接,可以调用服务器上的php脚本。该脚本对数据库进行查询,并使用json_encode给出响应 以下是脚本: $result = mysql_unbuffered_query($query); if ($result){ while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $output[] = $row; } if($output!=null)
$result = mysql_unbuffered_query($query);
if ($result){
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$output[] = $row;
}
if($output!=null)
echo json_encode($output);
else
echo "0";
}
当响应很短时,一切都很好,但是当我有一个长响应(比如500个字符)时,我会收到一个不完整的json,如下示例所示:
[{"user":"1","password":"password","tel":"3333333333","description":"some text, some text, some text","data":"2013-10-13 09:53:54"}, {"user":"1","password":"password","tel":"3333333333","description":"some text, so
在我的iOS应用程序中,我使用以下代码解码json:
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
如果我收到一个完整的json,一切正常,否则如果我收到一个不完整的json,我会发送一个新的请求。当json内容非常长时,接收到的json是不完整的,但有时,在一些请求之后,响应仍然是良好的
/*更新问题*/
执行请求:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:advertURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *queryString = [NSString stringWithFormat: @"%@", query];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
myConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
获取响应:
//in NSURL method didReceiveResponse
ResponseData = [[NSMutableData alloc] init];
//in NSURL method didReceiveData
[ResponseData appendData:data];
NSString *result = [[NSString alloc] initWithData:ResponseData encoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:Responsedata options:kNilOptions error:&error];
if(!json){
//incomplete json!
}
else{
//good json!
}
为什么会这样?我怎样才能解决这个问题
希望我自己解释一下,谢谢。当人们使用
nsurconnectiondatadelegate
方法(或NSURLSessionDataDelegate
方法)时,这个问题很常见,但没有意识到可能需要多次调用didReceiveData
来接收整个负载
因此,您可以做的是:
- 在
中实例化一个didReceiverResponse
NSMutableData
- 让
仅将数据附加到didReceiveData
,认识到对于较大的有效负载,可能需要多次调用此方法才能接收所有数据;及NSMutableData
- 在
(如果使用connectiondFinishLoading:
;如果使用NSURLConnection
,请使用NSURLSession
方法),然后在收到所有数据后继续解析URLSession:task:didpleteWither: