iOS中来自JSON的响应不完整

时间:2015-11-25 14:28:47

标签: ios json xcode

我对ion在iOs中收到的回复有疑问。 我不知道是不是因为有很多关于WebService的信息,但是Json的反应并不好。我收到一个答案,但是当我用变量NSMutableData * d检查数据字符串时,它是不完整的,而在*响应中,它不能用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];

答案是:

- (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];
}

1 个答案:

答案 0 :(得分:1)

只要收到一大块数据,就会调用saveAssociated委托方法。我们无法保证您在第一次通话时会收到完整的回复。

正确的方法是收集connection:didReceiveData:中的数据,然后在connection:didReceiveData:处理

您的代码应如下所示:

connectionDidFinishLoading: