Iphone JPEG数据流不包含使用NSURLConnection的图像

Bro*_*die 2 iphone jpeg nsurlconnection

我之前通过使用dataWithContentsOfURL下载jpg然后writeToFile来保存它来为我的应用程序下载图像.

我最近;开始使用NSURLConnetion做同样的事情,但现在我得到了以下错误和崩溃:

损坏的JPEG数据:87个无关字节JPEG数据流不包含图像

我知道这些图像并不严重,因为应用程序正在使用以前的方法下载它们.这是我的代码:

-(void) downloadSave {

    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    NSString *tempString = [[NSString alloc]initWithFormat:@"http://www.mysite.com/%@.jpg",chartFileName];
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:tempString]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:10.0];
    // create the connection with the request
    // and start loading the data

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        mutableData = [[NSMutableData data] retain];
        self.image = nil;
        NSLog(@"connection exists");
        [NSURLConnection connectionWithRequest:theRequest delegate:self];

    } else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error" message:@"There was an error contacting the chart servers. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        [activityIndicator stopAnimating];


    }




//  NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
//                                                       NSUserDomainMask, YES);

//  NSString *docsPath = [paths objectAtIndex:0];
//  NSString *downloadPath = [[[NSString alloc]initWithFormat:@"http://www.mysite.com/%@.jpg",chartFileName]autorelease];
//  downloadedChartData = nil;


    [pool drain];
    [pool release];




}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    NSLog(@"got to connection did receive response");
    [mutableData setLength:0];
}




- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [mutableData appendData:data];
//  NSLog(@"got some data, total: %i",mutableData.length);
}


- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
 //   [connection release];
    // receivedData is declared as a method instance elsewhere
   // self.mutableData = nil;

    // inform the user
    //NSLog(@"Connection failed! Error - %@ %@",
      //    [error localizedDescription],
        //  [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[mutableData length]);
    [connection release];
    // release the connection, and the data object
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    self.image = nil;

    NSString *savePath = [[[NSString alloc]initWithFormat:@"%@/%@.jpg",docsPath, chartFileName]autorelease];

    [mutableData writeToFile:savePath atomically:YES];
    self.mutableData = nil;
Run Code Online (Sandbox Code Playgroud)

ton*_*lon 8

您正在使用相同的委托初始化和启动两个 NSURLConnections.由于您的委托方法不检查哪个连接称为它们,因此您将在一个NSMutableData实例中混合两次图像的字节.

// Creates, initializes and starts an instance of NSURLConnection    
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
...
// Creates, initializes and starts another instance of NSURLConnection, with same request and delegate
[NSURLConnection connectionWithRequest:theRequest delegate:self];
Run Code Online (Sandbox Code Playgroud)

两个连接都在同一个委托实例上发出相同的实现,这意味着它们的数据以随机顺序写入相同的NSMutableData.

我建议简单地摆脱这条线:

[NSURLConnection connectionWithRequest:theRequest delegate:self];
Run Code Online (Sandbox Code Playgroud)

另一件事:你为什么要使用自动释放池downloadSave?如果从主线程中调用它,则在该池中只有一个NSURLRequest自动释放.如果你从另一个线程调用它,你必须小心,该线程的runloop设置并运行,或者你根本不会收到任何委托回调.