Iphone-SBJson returns null responseData for the connection which get late response in multiple request sending

StackOverflow https://stackoverflow.com/questions/13585119

Pergunta

Here, I tried to send Asynchronous call to python server using SBJson framework. For continuous multiple call with same request, gives null value in response string.

here, what I tried :

- (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];
}

After tracing NSlog responses, I found this, If I send same request 3 times (by pressing Update detail button) connectionDidFinishLoading should call 3 times and it is calling it. but for any (one) request the respective response data returns null. Thats why the JSON stated below

JSONValue failed. Error trace is: ( "Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x909d4b0 {NSLocalizedDescription=Unexpected end of string}"

How can I overcome from this scenario? or Is there anything wrong in the code?

Thanks!

Foi útil?

Solução

Your class is not re-entrant as there's only one reference to responseData. If two requests run at the same time Bad Things Will Happen. For this to work you'll need to either put your requestData in a dictionary keyed by the NSURLConnection, or create another instance of your downloader for each request.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top