开发者

NSURLConnection appends random characters to the response

At one place in my app, I initialize an asynchronous request using NSURLConnection:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self.URLs objectForKey:@"API URL"]]
    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

and fetch the result:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (responseData == nil) {
        responseData = [[NSMutableData allo开发者_JAVA百科c] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
    NSLog(@"%s", [data bytes]);
}

The problem is that sometimes random data is being appended to the actual data returned by the server. Sometimes, the log message as well as the actual output (after conversion to a NSString object in connectionDidFinishLoading:connection) contain some part of some header, "CFNetwork" or just arbitrary bytes/characters.

Is this a known bug? Has anyone encountered this before and knows how to work around this? Is there anything I might be doing wrong?


You need to append '0' character to limit the string if you use it as an c-String (null terminator).

From one of my projects:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   char temp[] = {0};
   [receivedData appendBytes:temp length:1];

   // etc your usual code here
}

Gave me a lot of headaches, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜