[英]The response in iOS from JSON is not complete
I have a problem with the response received by Json in iOs. 我对Json在iOs中收到的响应有疑问。 I don't know if it is because there is lot of informations concerning the WebService, but the response from Json is not good.
我不知道是否是因为有很多有关WebService的信息,但是Json的响应不是很好。 I receive an answer, but when I check the string of the data with the variable NSMutableData *d, it is not complete, and in the *response, it can not init with the JSONObjectWithData.
我收到一个答案,但是当我使用变量NSMutableData * d检查数据的字符串时,它并不完整,并且在* response中,它无法使用JSONObjectWithData进行初始化。
NSLog(@"Request: %@", bytes);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSData *requestData = [NSData dataWithBytes:[bytes UTF8String] length:[bytes length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:request delegate:self];
And the answer : 答案是:
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableData *d = [NSMutableData data];
[d appendData:data];
NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
NSError *error;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:d options:kNilOptions error:&error];
}
The connection:didReceiveData:
delegate method is called whenever a chunk of data is received. 每当接收到大块数据时,都会调用
connection:didReceiveData:
委托方法。 There is no guarantee that you will receive the complete response in the first call. 无法保证您会在第一个电话中收到完整的回复。
The right approach is to collect the data in the connection:didReceiveData:
and then process it in connectionDidFinishLoading:
正确的方法是收集
connection:didReceiveData:
的数据,然后在connectionDidFinishLoading:
中对其进行处理connectionDidFinishLoading:
Your code should look something like this: 您的代码应如下所示:
...
self.receivedData = [NSMutableData data];
...
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receivedData appendData:data]
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.