2

我正在使用NSURLConnection. 我将委托设置为self,并实现方法connection:didReceiveDataconnectionDidFinishLoading。收到数据后,我将其存储在一个NSMutableData对象(称为input)中,然后在连接结束时,我使用它来创建位图。问题是我收到了数据,connection:didReceiveData但它是空的connection:DidFinishLoading。我该如何解决?

- (void)start
{
    NSURL *url = [NSURL URLWithString:src];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    connection = [[NSURLConnection alloc] initWithRequest:request
                                                 delegate:self
                                         startImmediately:YES];
}

- (void)connection:(NSURLConnection *)conn
    didReceiveData:(NSData *)d
{
    NSLog(@"Data Received: %@", d);//This prints the correct data
    //Add data chunk to input
    [input appendData:d];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
    CPLog(@"Finished Receiving bitmap from server. Data received with length %d: %@", [input length], input);//this prints length 0 and a value of (null)
    CFDataRef imgData = (__bridge CFDataRef) input;
    CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData (imgData);
    CGImageRef image;
    if (!imgDataProvider)
    {
        NSLog(@"Request Failed!");//happens every time
        [callback handleBitmap:nil];
        return;
    }

    image = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);


    [callback handleBitmap:image];
    return;

}
4

1 回答 1

5

input您应该为属性分配内存。通常在开始新的 url 连接之前完成:

- (void)start
{
    self.input = [NSMutableData data];
    // .... init and start url connection
}
于 2012-10-10T21:42:43.940 回答