0

I'm trying to preview a downloaded file to system and the program crashes when performing the method called previewController:previewItemAtIndex:. From what I assumed is that is releasing the previewcontroller before it is displayed, but this error does not occur when the file is already in the documents folder. It only happens when trying to open the file right after it has been downloaded.

Here is the code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

NSUInteger row = [indexPath row];
NSUInteger count = [listSessionsST count];

[tableView deselectRowAtIndexPath:indexPath animated:YES];


    Signature *object = [listSessionsST objectAtIndex:row];


        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UILabel *lblInComplete = (UILabel*)[cell viewWithTag:4];
        UIImageView *imgCheck = (UIImageView*)[cell viewWithTag:3];

        //Sets the File Name
        self.File = [[[NSString stringWithFormat:@"%@_%@.%@",object.FileName,object.ModDate,object.Extension] 
                         componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];

        //Shows the loading screen while the file is being downloaded
        [DejalBezelActivityView activityViewForView:self.view withLabel:@"Downloading" width:0 LoadingType:@"Full"];
        [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;

        //Calls the method that will begin downloading the file 
        [self performSelector:@selector(startDownload:) withObject:object.Location afterDelay:0.2];

}


- (void)startDownload:(NSString *)strLocation{

NSString *filePath = [NSString stringWithFormat:@"%@/tmp/%@", NSHomeDirectory(),self.File];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];

if (fileExists)
{
    [DejalBezelActivityView removeViewAnimated:YES];
    //QuickLook APIs directly to preview the document 
    QLPreviewController *previewController = [[QLPreviewController alloc] init];
    previewController.dataSource = self;
    previewController.delegate = self;
    [[self navigationController] pushViewController:previewController animated:YES];
    [previewController release];
}
else
{
    NSDictionary *dictionary = [Signature downloadFile:self.File Path:strLocation];

    if ([dictionary valueForKey:@"Error"] == nil)
    {
        //If no error has occurred while downloading then preview the file.

        //QuickLook APIs directly to preview the document 
        QLPreviewController *previewController = [[QLPreviewController alloc] init];
        previewController.dataSource = self;
        previewController.delegate = self;
        [[self navigationController] pushViewController:previewController animated:YES];
        [previewController release];
        [DejalBezelActivityView removeViewAnimated:YES];
    }
    else 
    {
        //If an error occurred while downloading then display message to user.
        [DejalBezelActivityView removeViewAnimated:YES];
        UIAlertView *alert = [[UIAlertView alloc]                        
                              initWithTitle:@"" 
                              message:[dictionary valueForKey:@"Response"]
                              delegate:self 
                              cancelButtonTitle:@"Ok" 
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
  }
}

// Returns the number of items that the preview controller should preview
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{
    return 1;
}

// returns the item that the preview controller should preview
- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{

     NSString *path = [NSString stringWithFormat:@"%@/tmp/%@", NSHomeDirectory(),self.File];
    return [NSURL fileURLWithPath:path];
}


The method that downloads the file and saves it to the tmp folder 
---------------------------------------------------------------
+ (NSDictionary *)downloadFile:(NSString *)strFile Path:(NSString *)strPath{

float freeSpace = 0.0f;  
NSError *error = nil;  
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[NSString stringWithFormat:@"%@/tmp", NSHomeDirectory()]
                                                                                   error: &error];  
if (dictionary) 
{  
    NSNumber *fileSystemFreeSizeInBytes = [dictionary objectForKey: NSFileSystemFreeSize];  
    freeSpace = [fileSystemFreeSizeInBytes floatValue];  
}
else
{ 
    //Handle error
    NSLog(@"Error;%@",error);
    return [NSDictionary dictionaryWithObjectsAndKeys:@"An error has occurred while downloading the file.",@"Response",@"Y",@"Error", nil];
}  

if (freeSpace > 0.0f)
{
    NSDictionary *dict = nil;
    BOOL blnHasErroroccurred = NO;

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

    NSString *encoded = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                            (CFStringRef)strPath,
                                                                            NULL,
                                                                            (CFStringRef)@"!*'\"();:@&=+$,/?%#[]%",
                                                                            kCFStringEncodingUTF8 );

    NSString *strURL = [NSString stringWithFormat:@"%@/DataTransfer/DownloadFile?EMP_ID=%@&FilePath=%@", 
                        appDelegate.ServerAddress,
                        appDelegate.UserId,
                        encoded];

    [encoded release];

    NSURL *url = [NSURL URLWithString:strURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                                                           cachePolicy: NSURLRequestUseProtocolCachePolicy 
                                                       timeoutInterval:20.0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSURLResponse* response = nil;
    NSError* resultError = nil;

    NSData* dataResult = [NSURLConnection sendSynchronousRequest:request 
                                         returningResponse:&response 
                                                     error:&resultError];

    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

    if ([httpResponse statusCode] == 200) 
    {
        @try 
        {
            if (dataResult.length < freeSpace) 
            {
                //Get the tmp directory
                NSFileManager *fileManager =[NSFileManager defaultManager];
                NSString *fileName = [NSString stringWithFormat:@"%@/tmp/%@", NSHomeDirectory(),strFile];

                //Write the data to using the tmp directory
                BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataResult attributes:nil];       

                if(filecreationSuccess == YES)
                {
                    dict = [NSDictionary dictionaryWithObjectsAndKeys:@"",@"Response",nil,@"Error", nil];
                }   
                else
                {
                    blnHasErroroccurred = YES;
                }
            }
        }
        @catch (NSException *exception)
        {
            blnHasErroroccurred = YES;
        }
    }
    else 
    {
        blnHasErroroccurred = YES;
    }

    if(blnHasErroroccurred == YES)
    {
        dict  = [NSDictionary dictionaryWithObjectsAndKeys:@"An error has occurred while downloading the file.", @"Response", @"Yes",@"Error",nil];
    }

    [dataResult release];
    return dict;
}
else
{
    return [NSDictionary dictionaryWithObjectsAndKeys:@"Not enough disk space to download file.",@"Response",@"Y",@"Error", nil];
}
}
Angie
  • 475
  • 2
  • 6
  • 20
  • Is there any solution to this type of behavior? – Angie Sep 05 '12 at 17:04
  • There's a LOT of code going on here. To start off, have you tried Logging the path variable you generate before passing it to fileUrlForPath? – valheru Oct 03 '12 at 21:08

0 Answers0