我正面临着问题。我正在发送Asynchronus NSUrlrequest调用,但作为回报,我得到了多次响应json的某些部分
有人可以帮我解决我的错误。
码
NSString *_query = @"http://abc.com/index.php";
NSData *myRequestData = [NSData dataWithBytes:[_requestString UTF8String]
length:[_requestString length]];
__block NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:_query]];
[request setHTTPMethod: @"POST" ];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData ];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timeOutTimer forMode:NSDefaultRunLoopMode];
响应
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// check is response is a valid JSON?
NSError *error;
id jsonObj = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:&error];
BOOL isValid = [NSJSONSerialization isValidJSONObject:jsonObj];
NSString *content = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"Content: %@",content);
if (isValid)
{
NSDictionary *data = [content JSONValue];
}
[content release];
}
答案 0 :(得分:2)
当客户端收到数据时,会调用此回调函数:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
didReceiveData在接收数据时为您提供数据,并且可以使用数据块多次调用。
委托定期发送连接:didReceiveData:messages 收到数据。代表实施负责 用于存储新接收的数据。
从那些文档:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
完成所有操作后,将调用connectionDidFinishLoading,您可以使用附加的数据。
最后,如果连接成功下载请求,则 delegate收到connectionDidFinishLoading:消息。该 代表将不再收到有关连接和消息的消息 NSURLConnection对象可以被释放。