0

我面临着奇怪的问题。我正在发送 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];
}
4

1 回答 1

2

当客户端接收到数据时,将调用此回调:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

didReceiveData 在接收数据时为您提供数据,并且可以使用数据块多次调用。

NSURLConnection 文档

接收到数据时,委托会定期发送 connection:didReceiveData: 消息。委托实现负责存储新接收到的数据。

从那些文档中:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

完成后,将调用 connectionDidFinishLoading 并且您的附加数据已准备好供您使用。

最后,如果连接成功下载请求,代理会收到 connectionDidFinishLoading: 消息。委托将不会再收到有关连接的消息,并且可以释放 NSURLConnection 对象。

于 2012-08-21T11:32:25.957 回答