0

在这里,我尝试使用SBJson 框架向 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 失败。错误跟踪是:(“错误域 = org.brautaset.JSON.ErrorDomain 代码 = 11 \“字符串意外结束\” UserInfo = 0x909d4b0 {NSLocalizedDescription =字符串意外结束}”

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

谢谢!

4

1 回答 1

0

您的课程不可重入,因为只有一个对 responseData 的引用。如果两个请求同时运行,就会发生坏事。为此,您需要将您的 requestData 放入由 NSURLConnection 键入的字典中,或者为每个请求创建另一个下载器实例。

于 2012-12-12T15:01:21.343 回答