我正在使用NSURLConnection调用服务器请求JSON数据。
出于某种原因,我得到了部分回复。如果我通过浏览器点击了网址,则响应正确。奇怪的是它只在某个时候发生。所以我很难调试这个问题。
然后当因为响应未完成时,我收到以下错误: 错误域= NSCocoaErrorDomain代码= 3840"无法完成操作。 (可可误差3840。)" (字符0周围的值无效。)UserInfo = 0xa4634a0 {NSDebugDescription =字符0周围的值无效} { NSDebugDescription ="字符0周围的值无效。&#34 ;; } 的
我想这也可能是服务器本身的一个问题。这是我的代码:
-(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];
}
}
提前致谢。
答案 0 :(得分: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
}
始终实施所有四种委托方法。