Iphone-SBJson为连接返回null responseData,该连接在多个请求发送中得到延迟响应

时间:2012-11-27 13:18:42

标签: iphone ios json ipad sbjson

在这里,我尝试使用SBJson framework向python服务器发送异步调用。对于具有相同请求的连续多次调用,在响应字符串中提供null值。

这里,我尝试了什么:

- (NSURLConnection *) GetHttpConnection:(NSString *)Path:(NSDictionary *)requestData:(UIView *)appView {
    NSString *jsonReq = nil;
    NSData *reqData = nil;

    if (requestData != nil) {
        jsonReq = [requestData JSONRepresentation];
        reqData=[NSData dataWithBytes:[jsonReq UTF8String] length:[jsonReq length]];
    }
    NSString *urlString = [NSString stringWithFormat:@"%@/%@", URL, Path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if (reqData) {
        [request setHTTPBody:reqData];
    }
    [request setHTTPMethod:@"POST"];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
        responseData = [[NSMutableData data] retain];
    }
    return connection;
 }

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Connection Finish Loading >>>>> %@",responseString);    
    responseData = nil;
    if (responseString && [responseString JSONValue] != nil) {
       // process response string and send response back to delegate method
    }
  }


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData*)data {
    [responseData appendData:data];
}

追踪NSlog回复后,我发现了这个, 如果我发送相同的请求3次(通过按更新详细信息按钮) connectionDidFinishLoading应拨打3次呼叫它。但是对于任何(一个)请求,相应的响应数据都返回null。这就是为什么JSON如下所述

  

JSONValue失败。错误跟踪是:(       “Error Domain = org.brautaset.JSON.ErrorDomain Code = 11 \”字符串的意外结束\“UserInfo = 0x909d4b0 {NSLocalizedDescription = Unexpected   字符串结尾}“

我如何克服这种情况?或者代码中有什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您的类不可重入,因为只有一个对responseData的引用。如果两个请求同时运行Bad Things Will Happen。为此,您需要将您的requestData放入由NSURLConnection键入的字典中,或者为每个请求创建下载器的另一个实例。