1

我正在使用 NSURLConnection 调用请求 JSON 数据的服务器。

出于某种原因,我得到了部分回复。如果我通过浏览器点击网址,则响应正确。奇怪的是它只在某个时候发生。所以我很难调试这个问题。

然后当因为响应不完整时,我收到以下错误: 错误域 = NSCocoaErrorDomain 代码 = 3840“操作无法完成。(可可错误 3840。)”(字符 0 周围的值无效。) UserInfo = 0xa4634a0 {NSDebugDescription =字符 0 周围的值无效。} { NSDebugDescription = "字符 0 周围的值无效。"; }

我想这也可能是服务器本身的问题。这是我的代码:

-(void) getShareHistory:(NSString *)range paging:(NSInteger *)page{
     NSString *post = [NSString stringWithFormat:@"range=%@&paging=%@",
                      range,
                      [NSString stringWithFormat:@"%ld",(long)page]];
     NSString *url = [NSString stringWithFormat:@"http://www/domai.com/handle_share_links.php?action=history"];
     NSData *post_data = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
     NSString *postLength = [NSString stringWithFormat:@"%d", [post_data length]];
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
     [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
     [request setURL:[NSURL URLWithString:url]];
     [request setHTTPMethod:@"POST"];
     [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
     [request setHTTPBody:post_data];

     self.shareHistoryConn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)response{
     NSString *strData = [[NSString alloc]initWithData:response encoding:NSASCIIStringEncoding];
     NSLog(@"response %@",strData);
     NSError *jsonParsingError = nil;
     if(connection == self.shareHistoryConn)
     {
        NSArray *data = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&jsonParsingError];
    if(!jsonParsingError)
    {
        [[self delegate] onGetShareHistorySuccess:data];
    }else{
        [[self delegate] onGetShareHistoryFailed:jsonParsingError];
    }
}

提前致谢。

4

1 回答 1

3

你看到的是正常行为。didReceiveData可以调用任意次数。继续积累数据直到获得connectionDidFinishLoading.

标准的委托结构是这样的:

- (void) connection:(NSURLConnection *)connection
        didReceiveResponse:(NSURLResponse *)response {
    // connection is starting, clear buffer
    [self.receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection
        didReceiveData:(NSData *)data {
    // data is arriving, add it to the buffer
    [self.receivedData appendData:data];
}

- (void)connection:(NSURLConnection*)connection
        didFailWithError:(NSError *)error {
    // something went wrong, clean up interface as needed
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // all done, we are ready to rock and roll
    // do something with self.receivedData
}

始终实现所有四个委托方法。

于 2013-04-13T03:25:33.627 回答