user717452
user717452

Reputation: 111

Add Completion Handler for when PDF has been downloaded

UPDATE: At a suggestion, I tried implementing a NSURLSession to download and then draw the file. I have this now in my code, and it mostly works, but I've found if it is more than 1MB, it simply won't draw. I've also found if there are multiple pages, it skips to the second page for some reason to start off with. Do y'all see anything wrong?:

 NSString *theURL = [self.entry[@"SermonPDF"] url];
        /*sermonPDFURL = [NSURL fileURLWithPath:_sermonString];
         self.arrayOfVerses = @[@"allverses"];
         
         CGPDFDocumentRef pdfDocument = [self openPDF:sermonPDFURL];
         [self drawDocument:pdfDocument];*/
        NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

        NSURLSession *delegateFreeSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

            [[delegateFreeSession dataTaskWithURL: [NSURL URLWithString: theURL]
                               completionHandler:^(NSData *data, NSURLResponse *response,
                                                   NSError *error) {
                NSLog(@"Sermon error %@", error.description);
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[self.entry valueForKey:@"DateOfService"]] stringByAppendingString:@".pdf"];
                [data writeToFile:pdfPath atomically:YES];
                [self drawingSermonFinally];

                              
                               }] resume];

-(void)drawingSermonFinally {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[self.entry valueForKey:@"DateOfService"]] stringByAppendingString:@".pdf"];
    self.arrayOfVerses = @[@"allverses"];
    
    CGPDFDocumentRef pdfDocument = [self openPDFLocal:pdfPath];
    [self drawDocument:pdfDocument];
    
}

My app uses the following code to display a PDF in tvOS app:

 CGPDFDocumentRef pdfDocument2 = [self openPDF:[NSURL URLWithString:@"https://pdfislistedhere"]];
        [self drawDocument:pdfDocument2];

However, it seems it tries to draw too quickly. Is there a way to be able to add a completion handler to my code listed below for the CGPDFDocumentRef? This was code that I was helped with and can't figure out if there is a good method to go about having it wait to run drawDocument:pdfDocument until after the PDF has actually been downloaded? as of now, it will simply do nothing, but run all checks and logs as though it was successful.

- (CGPDFDocumentRef)openPDF:(NSURL*)NSUrl {
    CFURLRef url = (CFURLRef)CFBridgingRetain(NSUrl);
    
    CGPDFDocumentRef myDocument;
    myDocument = CGPDFDocumentCreateWithURL(url);
    if (myDocument == NULL) {
        NSLog(@"can't open %@", NSUrl);
        CFRelease (url);
        return nil;
    }
    CFRelease (url);
    
    if (CGPDFDocumentGetNumberOfPages(myDocument) == 0) {
        CGPDFDocumentRelease(myDocument);
        return nil;
    }
    
    return myDocument;
}
- (void)drawDocument:(CGPDFDocumentRef)pdfDocument
{   NSLog(@"draw document");
    theImageView.hidden = YES;
    // Get the total number of pages for the whole PDF document
    int  totalPages= (int)CGPDFDocumentGetNumberOfPages(pdfDocument);

    if ([[self.arrayOfVerses firstObject] isEqualToString:@"allverses"]) {
        NSLog(@"draw document all verses %d", totalPages);
        self.pages = totalPages;
        self.subtractingPages = totalPages - 1;

        NSMutableArray *pageImages = [[NSMutableArray alloc] init];
        
        // Iterate through the pages and add each page image to an array
        for (int i = 1; i <= totalPages; i++) {
            // Get the first page of the PDF document
            CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, i);
            CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
            
            // Begin the image context with the page size
            // Also get the grapgics context that we will draw to
            UIGraphicsBeginImageContext(pageRect.size);
            CGContextRef context = UIGraphicsGetCurrentContext();
            
            // Rotate the page, so it displays correctly
            CGContextTranslateCTM(context, 0.0, pageRect.size.height);
            CGContextScaleCTM(context, 1.0, -1.0);
            CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));
            
            // Draw to the graphics context
            CGContextDrawPDFPage(context, page);
            
            // Get an image of the graphics context
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            [pageImages addObject:image];
        }
        // Set the image of the PDF to the current view
        [self addImagesToScrollView:pageImages];
    }
    else {
        self.pages = [self.arrayOfVerses count];
        self.subtractingPages = self.pages - 1;

        NSLog (@"total pages %ld", (long)self.pages);
        NSMutableArray *pageImages = [[NSMutableArray alloc] init];
        
        
        [pageImages removeAllObjects];
        
        //Getting slide numbers to be used
        NSString *text = self.selectedCountry;
        NSString *substring = nil;
        
        NSRange parenRng = [text rangeOfString: @"(?<=\\().*?(?=\\))" options: NSRegularExpressionSearch];
        
        if ( parenRng.location != NSNotFound ) {
            substring = [text substringWithRange:parenRng];
            NSLog(@"Substring %@", substring);
        }
        
        
        // Iterate through the pages and add each page image to an array
        for (int i = 1; i <= totalPages; i++) {
            // Get the first page of the PDF document
            
            
            NSPredicate *valuePredicate=[NSPredicate predicateWithFormat:@"self.intValue == %d",i];
            
            if ([[self.arrayOfVerses filteredArrayUsingPredicate:valuePredicate] count]!=0) {
                // FOUND
                CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, i);
                CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
                
                // Begin the image context with the page size
                // Also get the grapgics context that we will draw to
                UIGraphicsBeginImageContext(pageRect.size);
                CGContextRef context = UIGraphicsGetCurrentContext();
                
                // Rotate the page, so it displays correctly
                CGContextTranslateCTM(context, 0.0, pageRect.size.height);
                CGContextScaleCTM(context, 1.0, -1.0);
                CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));
                
                // Draw to the graphics context
                CGContextDrawPDFPage(context, page);
                
                // Get an image of the graphics context
                UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                
                
                [pageImages addObject:image];
            }
            
            else  {
                //NOT FOUND
            }
            
        }
        // Set the image of the PDF to the current view
        [self addImagesToScrollView:pageImages];
    }
}

Upvotes: 0

Views: 58

Answers (0)

Related Questions