I am trying to combine 11 pdf files into a single pdf file.The following code i am using ,but in the final pdf only the first pdf is shown ...i nslogged the pdfurls and CGPDFDocumentRef in the loop and they are not nil all the time(in the loop).What may be the reason why only the first page is displayed in the final document
-(void)mergeDocuments
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *oldFile=[documentsDirectory stringByAppendingPathComponent:#"finalPdf.pdf"];
NSMutableData *data=[[NSMutableData alloc] init];
CGRect paperSize=CGRectMake(0,0,kDefaultPageWidth,kDefaultPageHeight);
UIGraphicsBeginPDFContextToData(data, paperSize, nil);
for (int pageNumber = 1; pageNumber <= 11; pageNumber++)
{
NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",pageNumber]] retain];
NSURL *pdfUrl = [[NSURL fileURLWithPath:pdfPath] retain];
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) pdfUrl);
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
CGContextDrawPDFPage (currentContext, newPage);
newPage = nil;
CGPDFDocumentRelease(newDocument);
newDocument = nil;
[pdfUrl release];
}
NSURL *finalUrl=[NSURL URLWithString:oldFile];
UIGraphicsEndPDFContext();
[data writeToURL:finalUrl atomically:YES];
}
It looks like your code assumes that there is only one page in each document, however it is asking for page pageNumber from each file as it opens it, and is therefore asking for page 1 from page_1.pdf, page 2 from page_2.pdf, page 3 from page_3.pdf, etc...
If you just want the first page from each document change this:
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
to this:
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, 1);
For what it's worth, I re-wrote your routine before I spotted this based on one that I already have (forgive me but it is in an ARC project so you'll have to re-do your memory management) as follows:
(NOTE: Error checking has been removed to make the code more readable!)
-(void)mergeDocuments {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *oldFilePath=[documentsDirectory stringByAppendingPathComponent:#"finalPdf.pdf"];
NSURL *oldFileUrl = [NSURL fileURLWithPath:oldFilePath];
CGContextRef context = CGPDFContextCreateWithURL((__bridge_retained CFURLRef)oldFileUrl, NULL, NULL);
for (int docNumber = 1; docNumber <= 11; docNumber++)
{
// Get the first page from each source document
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",docNumber]];
NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((__bridge_retained CFURLRef)pdfUrl);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1);
CGRect pdfCropBoxRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
// Copy the page to the new document
CGContextBeginPage(context, &pdfCropBoxRect);
CGContextDrawPDFPage(context, pdfPage);
// Close the source files
CGContextEndPage(context);
CGPDFDocumentRelease(pdfDoc);
}
// Cleanup
CGContextRelease(context);
}
If what you want is all pages of all the source PDF files, your for loop is wrong.
You loop counter 'pageNumber' runs from 1 to 11. You are using the same variable to open the corresponding file as well as to fetch a page from that pdf.
So, your for loop will produce a pdf with
1st page of 1st pdf, 2nd page of 2nd pdf,....,11th page of 11th pdf
If your 2nd - 11th pdf files do not have as many pages, the final output will obviously have only the first page of first pdf.
You need 2 for loops. One to iterate through pdf files and the other to iterate through each page of every pdf file.
for (int documentNumber = 1; documentNumber <= 11; documentNumber++)
{
NSString *pdfPath = [[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"page_%d.pdf",documentNumber]] retain];
NSURL *pdfUrl = [[NSURL fileURLWithPath:pdfPath] retain];
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) pdfUrl);
int numberOfPages = CGPDFDocumentGetNumberOfPages(newDocument);
for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++)
{
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
CGContextDrawPDFPage (currentContext, newPage);
//any other page rendering
newPage = nil;
}
CGPDFDocumentRelease(newDocument);
newDocument = nil;
[pdfUrl release];
}
Related
Using iOS-htmltopdf, i am able to convert DOC to PDF but i want single page PDF from doc file.
The reason is some content of one page gets into another page so only one page.
In NDHTMLtoPDF.m i use these 2 line of code then PDF page size becomes double
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if (webView.isLoading) return;
long pageHeight = [[webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"]longLongValue];
self.pageSize = CGSizeMake(595, webView.scrollView.contentSize.height/2);
.........
.........
.........
}
Firstly convert DOC to PDF using NDHTMLtoPDF.
Below delegate method will be called
- (void)HTMLtoPDFDidSucceed:(NDHTMLtoPDF*)htmlToPDF
{
NSLog(#"HTMLtoPDF did succeed (%# / %#)", htmlToPDF, htmlToPDF.PDFpath);
NSURL *pptURL = [NSURL fileURLWithPath:htmlToPDF.PDFpath];
NSURLRequest *request = [NSURLRequest requestWithURL:pptURL];
[myWebView loadRequest:request];
//now merge whole pages to one PDF
[self MergeToOnePagePDF:pptURL];
}
Now add these method:
-(void)MergeToOnePagePDF:(NSURL *)pdfURL
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfURL);
int pageCount = CGPDFDocumentGetNumberOfPages(pdf);
CGPDFPageRef pageRef = CGPDFDocumentGetPage(pdf, 1);
CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);
float pageHeight = pageRect.size.height;
pageRect.size.height = pageRect.size.height * pageCount;
NSMutableData* pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)pdfData);
CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, &pageRect, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
CGContextTranslateCTM(pdfContext, 0, pageRect.size.height);
for (int i = 1; i <= pageCount; i++)
{
pageRef = CGPDFDocumentGetPage(pdf, i);
CGContextTranslateCTM(pdfContext, 0, -pageHeight);
CGContextDrawPDFPage(pdfContext, pageRef);
}
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFile = [documentsDirectory stringByAppendingPathComponent:#"destination.pdf"];
[pdfData writeToFile: pdfFile atomically: NO];
}
EDIT : Merging pages into one page PDF credit goes to #iPDFDev
I have three options for you probably you might get your answer in any one of them.
1)check this link.MonkeyBread
2) With Pdflab you can split, combine, reorganize Pdf's.
3) All you have to do is open the doc file in preview, apple + c copies the page that you are on, apple + n., apple + v and you have the single page pdf.
I hope these help you to some extent.
I am creating pdf from UIView to pdf it works fine but i have scrollView with content which i want to convert to pdf but it only show visible part in pdf not the whole scrollView content. here is my code
-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [NSMutableData data];
// Get Scrollview size
CGRect scrollSize = CGRectMake(1018,76,scrollView.contentSize.width,scrollView.contentSize.height);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
THis gives you the visible portion of the UIScrollView
CGRect visibleRect;
visibleRect.origin = scrollView.contentOffset;
visibleRect.size = scrollView.bounds.size;
float theScale = 1.0 / scale;
visibleRect.origin.x *= theScale;
visibleRect.origin.y *= theScale;
visibleRect.size.width *= theScale;
visibleRect.size.height *= theScale;
so you can use this in UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
by some minor changes in the parameters.
(void)createPDFfromUIView:(UIScrollView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Get Scrollview size
CGRect scrollSize = CGRectMake(aView.origin.x,aView.origin.y,aView.contentSize.width,aView.contentSize.height);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, scrollSize, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
This code i used to make pdf from uiscrollview and it does help but it will not be as good as if we draw on pdf -- please have look -- Pdf from UIScrollView
- (void) createPDF
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *directroyPath = nil;
directroyPath = [documentsDirectory stringByAppendingPathComponent:#"temp"];
NSString *filePath = [directroyPath stringByAppendingPathComponent:#"test.pdf"];
// check for the "PDF" directory
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
} else {
[[NSFileManager defaultManager] createDirectoryAtPath:directroyPath
withIntermediateDirectories:NO
attributes:nil
error:&error];
}
CGContextRef pdfContext = [self createPDFContext:_scrollView2.bounds path:(CFStringRef)filePath];
NSLog(#"PDF Context created");
/*
Here limit of i is no of pages in your uiscrollview or
you can use hit and trial here because there is a
length of page is going to be equal to
the visible size of uiscrollView in your application
*/
for (int i = 0 ; i< 2 ; i++)
{
// page 1
CGContextBeginPage (pdfContext,nil);
//turn PDF upsidedown
CGAffineTransform transform = CGAffineTransformIdentity;
//here 365 is equal to the height of myScrollView.frame.size.height
transform = CGAffineTransformMakeTranslation(0, (i+1) * 365);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(pdfContext, transform);
//Draw view into PDF
[_scrollView2.layer renderInContext:pdfContext];
CGContextEndPage (pdfContext);
[_scrollView2 setContentOffset:CGPointMake(0, (i+1) * 365) animated:NO];
}
CGContextRelease (pdfContext);
}
- (CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path
{
CGContextRef myOutContext = NULL;
CFURLRef url;
url = CFURLCreateWithFileSystemPath (NULL, path,
kCFURLPOSIXPathStyle,
false);
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL (url,
&inMediaBox,
NULL);
CFRelease(url);
}
return myOutContext;
}
The easiest way to convert the scrollview content into a PDF file is to have a content view as the first subview of the scrollview and using that view to take a snapshot of the scrollview. The code in Swift would look like this:
func generatePDFdata(withView view: UIView) -> NSData {
let pageDimensions = view.bounds
let outputData = NSMutableData()
UIGraphicsBeginPDFContextToData(outputData, pageDimensions, nil)
if let context = UIGraphicsGetCurrentContext() {
UIGraphicsBeginPDFPage()
view.layer.render(in: context)
}
UIGraphicsEndPDFContext()
return outputData
}
You can then use the outputData to write into a PDF file:
outputData.write(to: pdfFileUrl, atomically: true)
I'm working on a pdf annotations application and i need to save the annotation so when i tried to save the annotations and the pdf content to a new pdf , the annotations are saved but the content of the pdf is not ? here is my function :
-(void)save_doc_as_pdf:(ReaderMainToolbar *)toolbar BackButton:(UIButton *)button
{
NSError *error;
NSString *PdfPath = [document.fileURL absoluteString];
NSString *newPath = [PdfPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
NSString *NewPdfPath = [thenewPath stringByReplacingOccurrencesOfString:#".pdf" withString:#"_1.pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:[document.fileURL path] options:NSDataReadingUncached error:&error];
if (pdfData == nil) {
NSLog(#"data is nil !!!!");
}
if (error)
{
NSLog(#"%#", [error localizedDescription]);
return;
}
else
NSLog(#"Data has loaded successfully.");
//If fails to create the new file, returns
if (![[NSFileManager defaultManager] createFileAtPath:NewPdfPath contents:pdfData attributes:nil])
{
return;
}
NSURL *url = [NSURL fileURLWithPath:newPath];
CGPDFDocumentRef pdf_document = CGPDFDocumentCreateWithURL ((__bridge_retained CFURLRef) url);
size_t count = CGPDFDocumentGetNumberOfPages(pdf_document);
if (count == 0)
{
NSLog(#"PDF needs at least one page");
return;
}
CGRect paperSize = CGRectMake(0, 0,842, 1190);
UIGraphicsBeginPDFContextToFile(NewPdfPath , paperSize, nil);
// CGPDFPageRef page = CGPDFDocumentGetPage(document, 1);
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// flip context so page is right way (landscape app)
CGContextScaleCTM(currentContext, 1, -1);
// Rotate the coordinate system (rotation = M_PI or -M_PI for landscape)
//CGContextRotateCTM(currentContext, rotation/ 2);
CGPDFPageRef page = CGPDFDocumentGetPage (pdf_document, 1); // grab page 1 of the PDF
CGContextDrawPDFPage (currentContext, page); // draw page 1 into graphics context
//flip context so annotations are right way
CGContextScaleCTM(currentContext, 1, -1);
//CGContextRotateCTM(currentContext, rotation / 2);
//Render the layer of the annotations view in the context
[startdraw.layer renderInContext:currentContext];
UIGraphicsEndPDFContext();
CGPDFDocumentRelease (pdf_document);
}
hello i find a solution for saving an annotaion on a pdf document and i want to shar it with you so here is the code :
-(void)save_the_pdf:(ReaderMainToolbar *)toolbar BackButton:(UIButton *)button{
NSMutableArray *URLsTableObject=[[NSMutableArray alloc] init];
NSMutableArray *URLsTable=[[NSMutableArray alloc] init];
NSUserDefaults *DataStoreUrls;
NSString *OriginalPdfName = [document.fileName stringByReplacingOccurrencesOfString:#".pdf" withString:#""];
NSString *OriginalPdfPath = [document.fileName stringByReplacingOccurrencesOfString:#".pdf" withString:#""];
NSString* thenewPath = [[NSBundle mainBundle] pathForResource:OriginalPdfPath ofType:#"pdf"];
NSString *NewPdfPath = [thenewPath stringByReplacingOccurrencesOfString:#".pdf" withString:#"_1.pdf"];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[[NSBundle mainBundle] URLForResource:OriginalPdfName withExtension:#"pdf"]);
const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
for(size_t page = 1; page <= numberOfPages; page++)
{
// Get the current page and page frame
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
// Draw the page (flipped)
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
CGContextDrawPDFPage(ctx, pdfPage);
CGContextRestoreGState(ctx);
if (page == currentPage) {
[startdraw.layer renderInContext:ctx];
}
}
UIGraphicsEndPDFContext();
CGPDFDocumentRelease(pdf);
//pdf = nil;
if (![[NSFileManager defaultManager] createFileAtPath:NewPdfPath contents:data attributes:nil])
{
return;
}
// Do something with the 'data'...
DataStoreUrls=[NSUserDefaults standardUserDefaults];
if([DataStoreUrls objectForKey:#"ALLURLS"]!=NULL){
URLsTableObject=[DataStoreUrls objectForKey:#"ALLURLS"];
int index=[URLsTableObject count];
URLsTable=[[NSMutableArray alloc] initWithArray:URLsTableObject];
[URLsTable insertObject:NewPdfPath atIndex:index];
[DataStoreUrls setObject:URLsTable forKey:#"ALLURLS"];
}else{
[URLsTable addObject:NewPdfPath];
[DataStoreUrls setObject:URLsTable forKey:#"ALLURLS"];
}
[DataStoreUrls synchronize];
}
Hi Im really having a hard time saving in my NSDocumentDirectory.Im using AGImagePickerby the way. Yes I was able to save this in NSDocumentDirectory. But how to save them uniquely ( in terms of their own then converting their names into oneSlotImages) or save them with their unique IDs then load them back. Sorry Im kinda new to this UIImagePickerControllerMediaURL thing., I think that would be my solution to my other problem for not overlaping them when saving. How to save this using their unique ID, or UIImagePickerControllerMediaURL.
for (int i = 0; i < info.count; i++) {
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
Thanks for the help. Much Appreciated.
You could always keep a list of used names and do something like this
int i = 1;
while([listOfUsedNames containsObject:nextAvailableTile]) {
nextAvailableTitle = [kDefaultImageName stringByAppendingFormat:#" %d", i];
i++;
}
// found an unused name
The URL for each image is unique right? So we can make use of this. Convert the URL into MD5 string (which form a unique identifier for each image). And save with that name (like "MD5string.png").
Why can't we use this?
Hope this helps you.
For converting to MD5, please create a file named NSString+MD5.h and put the code
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#interface NSString(MD5)
- (NSString *)MD5;
#end
in it.
Then in the NSString+MD5.m,
#import "NSString+MD5.h"
#implementation NSString(MD5)
- (NSString*)MD5
{
const char *ptr = [self UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(ptr, strlen(ptr), md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x",md5Buffer[i]];
return output;
}
#end
Import the NSString+MD5.h class where ever you want to use the MD5 function with normal NSString object.
In you code if you have the UIImagePickerControllerMediaURL string, since it is unique for every file you can convert in to MD5 String like
NSString *imgURL = [NSString stringWithString: UIImagePickerControllerMediaURL];
NSString *MD5String = [imgURL MD5];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", MD5String]];
Use that path to save your image file.
On Loading,
Convert the UIImagePickerControllerMediaURL into MD5 and check in the Documents directory for the file
// In this the UIImagePickerControllerMediaURL is the URL of media file to load
NSString *imgURL = [NSString stringWithString: UIImagePickerControllerMediaURL];
NSString *MD5String = [imgURL MD5];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", MD5String]];
Then do the checking with the fileExistsAtPath method of NSFileManager and if exists then load the file from the path. Thats it.
Note: For this you want to keep the UIImagePickerControllerMediaURL of the images you saved in documents directory locally somewhere in your app (In DB or NSUserDefaults) for make use of then at the time of loading.
Try this:
NSMutableString *imageName = [[[NSMutableString alloc] initWithCapacity:0] autorelease];
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
[imageName appendString:NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID))];
CFRelease(theUUID);
}
[imageName appendString:#".png"];
I am using the ImageDemo template and it works great if I code in an image from the bundle but when I try and load them from directories I have created in my app I have no luck.
Code:
- (AQGridViewCell *) gridView: (AQGridView *) aGridView cellForItemAtIndex: (NSUInteger) index
{
static NSString * PlainCellIdentifier = #"PlainCellIdentifier";
AQGridViewCell * cell = nil;
ImageDemoGridViewCell * plainCell = (ImageDemoGridViewCell *)[aGridView dequeueReusableCellWithIdentifier: PlainCellIdentifier];
if ( plainCell == nil )
{
plainCell = [[[ImageDemoGridViewCell alloc] initWithFrame: CGRectMake(0.0, 0.0, 200.0, 150.0)
reuseIdentifier: PlainCellIdentifier] autorelease];
plainCell.selectionGlowColor = [UIColor lightGrayColor];
}
NSString *fileName = [NSString stringWithFormat:#"%#/%#_tn.jpg",[manufacturerID stringValue], [[[self.collectionItems objectAtIndex:index] valueForKey:#"PhotoName"] stringByReplacingOccurrencesOfString:#" " withString:#"%20"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *savePath =[documentsPath stringByAppendingPathComponent:fileName] ;
NSData *imageData = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:savePath];
if (fileExists) {
imageData = [NSData dataWithContentsOfFile:savePath];
} else {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"NoImageAvailableThumbNail" ofType:#"png"];
imageData = [NSData dataWithContentsOfFile:filePath];
}
UIImage *myImage = [UIImage imageWithData:imageData];
NSLog(#"%#", myImage);
if (myImage==nil) {
NSLog(#"NO IMAGE");
}
plainCell.image = myImage;
cell = plainCell;
return ( cell );
}
I code I am using to pull the image data I know works because I use it all over in other places in my app and I am checking for nil when I set the property on the AQGridViewCell:
- (void) setImage: (UIImage *) anImage
{
_imageView.image = anImage;
[self setNeedsLayout];
}
I don't see the check for a nil UIImage in your example there. Are you certain it's being loaded correctly? Try creating the image on one line and setting it on another so you can see it being created in the debugger. For reference, I do something similar with cached book cover images in the Kobo app, and that works. One difference though is that I use the C methods to load a UIImage from a PNG file. Something like UIImageFromPNGData(), off the top of my head (sorry replying by iPhone right now).
The only other thing I can think to check is whether the image view is hidden for some reason. Printing it in the debugger should tell you that, along with it's size, layout, etc.