我正在使用NSURLConnection
. 我将委托设置为self
,并实现方法connection:didReceiveData
和connectionDidFinishLoading
。收到数据后,我将其存储在一个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;
}