在iPhone中下载较大的pdf(> 2MB)时,我的应用程序崩溃了 [英] My app crashes when downloading large pdfs (>2MB) in iphone

查看:80
本文介绍了在iPhone中下载较大的pdf(> 2MB)时,我的应用程序崩溃了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序可以很好地下载小型Pdf并将其显示在WebView中,但是当我获取大小超过2 MB的PDF的url时,它每次都会崩溃.

My app is working fine for downloading small Pdf's and showing them in WebView but when i fetch url of pdfs having size more than 2 MB it crashes everytime.

代码:-

@implementation SecondViewController

@synthesize scrollView,receivedData,myIndicator;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{   
    [receivedData appendData:data]; 
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    myIndicator.hidesWhenStopped = YES;
    [myIndicator startAnimating];

    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"iphone_landscape.png"]];
    self.view.backgroundColor = background;
    [background release];   

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:150.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        receivedData = [[NSMutableData data] retain];
    }

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    int x=10,y=50;

    appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];

    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 45,320, 480)];   
    scrollView.contentSize = CGSizeMake(320,5000);
    scrollView.showsVerticalScrollIndicator = YES;

    for (Litofinter *lito in appDelegate.bookArray) {
        if([appDelegate.currentButtonPressed isEqualToString:lito.cName])
        {
            NSLog(@"Count == %d ===",[lito.productsArray count]);
            for (Products *prod in lito.productsArray) {

                NSString * urlString = [prod.thumbnail stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                NSURL * imageURL = [NSURL URLWithString:urlString];

                NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
                UIImage * image = [UIImage imageWithData:imageData];

                [myIndicator stopAnimating];
                [myIndicator removeFromSuperview];

                UIButton *imageButton = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
                [imageButton setFrame:CGRectMake(x, y, 140, 190)];
                [imageButton setImage:image forState:UIControlStateNormal];
                [imageButton setTitle:prod.pdf forState:UIControlStateNormal];
                [imageButton addTarget:self action:@selector(onTapBook:) forControlEvents:UIControlEventTouchUpInside];

                [scrollView addSubview:imageButton];

                x = x + 160;

                if(x >300)
                {
                    y = y +250;
                    x = 10;

                }
            }
        }
    }
    [self.view addSubview:scrollView];

    [connection release];
    [receivedData release];


}

-(void)onTapBook:(id)sender{

    UIButton *button = (UIButton *) sender;
    appDelegate.currentBookPressed = [button currentTitle];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Ver Catalogo!" message:@"" delegate:self cancelButtonTitle:@"Cancelar" otherButtonTitles:@"Ver on-line",@"Descargar",nil];
    [alert show];
}

// when I click on Descargar button i.e. download it goes to next PdfShowViewController

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
{  

    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];  

    if([title isEqualToString:@"Ver on-line"])  
    { 
        viewController2 = [[PdfShowViewController alloc]initWithNibName:@"PdfShowViewController" bundle:nil];
        [self presentModalViewController:viewController2 animated:YES];

    }  

    else if([title isEqualToString:@"Descargar"])  
    {       
        viewController2 = [[PdfShowViewController alloc]initWithNibName:@"PdfShowViewController" bundle:nil];
        [self presentModalViewController:viewController2 animated:YES];
    }  

} 


-(IBAction)onTapBack{
    [self dismissModalViewControllerAnimated:YES];
}


- (void)dealloc {
    [super dealloc];
    [scrollView release];
}


@end

// here i am showing the pdf on a webView and downloading them

@implementation PdfShowViewController

@synthesize pdfWebview,myIndicator,progress,receivedData,DownloadRequest,DownloadConnection,downloadLabel,openURL;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];
    NSLog(@"Data === %ld",receivedData);

    NSInteger receivedLen = [data length];
    bytesReceived = (bytesReceived + receivedLen);
    NSLog(@"received Bytes ==  %f",bytesReceived);

    if(expectedBytes != NSURLResponseUnknownLength) 
    {
        NSLog(@"Expected Bytes in if ==  %f",expectedBytes);
        NSLog(@"received Bytes in if ==  %f",bytesReceived);

        float value = ((float) (bytesReceived *100/expectedBytes))/100;
        NSLog(@"Value ==  %f",value);
        progress.progress=value;
    }

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [connection release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    expectedBytes = [response expectedContentLength];
    NSLog(@"%f",expectedBytes);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [myIndicator stopAnimating];
    [myIndicator removeFromSuperview];
    [progress setHidden:YES];
    [downloadLabel setHidden:YES];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"MayankPdf.pdf"];

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];

    [self.receivedData  writeToFile:pdfPath atomically:YES];

    [connection release];

    //Now create Request for the file that was saved in your documents folder

    NSURL *url = [NSURL fileURLWithPath:pdfPath];

    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [pdfWebview setScalesPageToFit:YES];
    [pdfWebview loadRequest:requestObj];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];

    [downloadLabel setText:@"Downloading..."];
    [downloadLabel setHidden:NO];

    [myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    myIndicator.hidesWhenStopped = YES;
    [myIndicator startAnimating];

    NSLog(@"REquired --------------------------------%@",appDelegate.currentBookPressed);
    //  NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"The Url Stirng=======%@",urlString);

    NSURL *targetURL = [NSURL URLWithString:urlString];
    NSLog(@"Trageted String ------======++++++++%@",targetURL);
    DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
    DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];

    if (DownloadConnection) {
        receivedData = [[NSMutableData data]retain];
    }

    [pdfWebview setScalesPageToFit:YES];
    //  [pdfWebview loadRequest:DownloadRequest];


}

-(IBAction)onTapBack
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {
    [super dealloc];
    [pdfWebview release];
    //  [receivedData release];
}


@end

我的解析器也不接受具有空格的URL,任何解决方案将不胜感激.在此先感谢

如果我写的东西不对,请原谅我,因为我在Iphone上不是很好.

Pardon me if have written something wrong as i am not very good in Iphone.

推荐答案

您可能已经超过了30MB的RAM限制,

you are probably exceeding the 30MB RAM limit,

您不应使用NSMutableData对象来重建完整文件,而应将其直接写入磁盘"以限制内存使用.

you shouldn't use a NSMutableData object to reconstruct the full file but write it directly on "disk" to limit memory usage.

激励你

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    @synchronized(connection) {
        m_downloadedBytes += [data length];
        CGFloat downloadProgress = ((CGFloat) m_downloadedBytes / (CGFloat) m_fileSize);
        [self setDownloadProgress:downloadProgress];        

        if (!m_fileHandle) {
            [data writeToURL:m_tmpTargetURL atomically:NO];
            m_fileHandle = [[NSFileHandle fileHandleForWritingToURL:m_tmpTargetURL error:NULL] retain];
            [m_fileHandle seekToEndOfFile];
        }
        else {
            [m_fileHandle writeData:data];

        }
    }
}

这篇关于在iPhone中下载较大的pdf(> 2MB)时,我的应用程序崩溃了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆