iOS QLPreviewController show pdf saved to file system - ios

I have QLPreviewController working if I show a PDF file system from my bundle on the project,
like this example
but If I want to show a PDF from the file system, it doesnt show it, how can I call a pdf file that I have just downloaded in my file system?
The code:
- (void)initPDFviewer
{
QLPreviewController *previewController=[[QLPreviewController alloc]init];
previewController.delegate=self;
previewController.dataSource=self;
[self presentModalViewController:previewController animated:YES];
[previewController.navigationItem setRightBarButtonItem:nil];
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
return 1;
}
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
//return 0;
//return url!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"paths :: %#", paths);
return 0;
}
So my problem is how to get the pdf [only pdf in the documents directory], how do i get this pdf?
thanks
thanks!

Change your init method to below.
-(id)init
{
if (self = [super init])
{
// arrayOfDocuments = [[NSArray alloc] initWithObjects:
// #"iOSDevTips.png", #"Remodel.xls", #"Core J2ME Technology.pdf", nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docPath = [paths lastObject];
NSArray *docArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:nil];
arrayOfDocuments = [[NSArray alloc] initWithArray:docArray];
}
return self;
}
Add this new method
-(NSString*)documentDirectoryPathForResource:(NSString*)aFileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:aFileName];
return fullPath;
}
And replace your method with my method
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
// Break the path into it's components (filename and extension)
NSString *path = [self documentDirectoryPathForResource:arrayOfDocuments[index]];
return [NSURL fileURLWithPath:path];
}
Code is self explanatory. Just create the array of all the documents that are in your document directory. And after that use that array to create the path and provide URL of that path to QLPreviewController

NSURL *fileURL = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *wordFilePath = [documentsDirectory stringByAppendingPathComponent:#"sample.doc"];
fileURL = [NSURL fileURLWithPath:wordFilePath];
return fileURL;

Related

How can I get the all images which are stored in NSDocumentsDirectory in iOS?

How can I retrieve all the images from NSDocumentsDirectory? I don't know the image name but I need to store all the images in NSMutableArray.
Try this dude
-(NSMutableArray*)pullOutAllImagesInDocumentsDirectory{
NSArray *listOfPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [listOfPaths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *imageFilePathsCollection = [[NSMutableArray alloc] init];
for (int imageIndex=0; imageIndex<filePathsArray.count; imageIndex++) {
NSString *strFilePath = [filePathsArray objectAtIndex:0];
if ([[strFilePath pathExtension] isEqualToString:#"png"]||
[[strFilePath pathExtension] isEqualToString:#"PNG"]||
[[strFilePath pathExtension] isEqualToString:#"jpg"]) {
[imageFilePathsCollection addObject:[filePathsArray objectAtIndex:imageIndex]];
}
}
return imageFilePathsCollection;
}
NOTE: it will give image url path. in order to get the image, you can use
[yourImageView setImage:[UIImage imageWithContentsOfFile:"Path Of Image"]];
I assuming you mean the Documents Directory specific to your app sandbox. If so you can access that directory using [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Cycle through that directory and look for files that have a .png or .jpg e.t.c. path extension.
i.e:
NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray *array = [[NSFileManager defaultManager] contentsAtPath:string];
for (NSString *doc in array) {
NSLog(#"%#", doc);
if ([doc.pathExtension isEqualToString:#"jpg"]) {
// Is jpg image obviously you want to search for different formats also
}
}

Can't save and load plist file

When i tried to create plist file('Checklist.plist') using following methods i can't see the file in the directory.
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory; }
- (NSString *)dataFilePath {
return [[self documentsDirectory] stringByAppendingPathComponent:#"Checklists.plist"];
}
Why i can't see the file on the directory? How can i solve this problem?
Did you save something in the file?
NSString *test = #"test";
[test writeToFile:[self dataFilePath] atomically:YES];
If you run this in a simulator, you can NSlog this file path, and than open finder, press cmd + shift + g paste the file path, don't include Checklist.plist, just documents file path, you will see the file you just create named Checklist.plist.
This is all my code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *testArray = [NSArray arrayWithObjects:#"test", nil];
[testArray writeToFile:[self dataFilePath] atomically:YES];
}
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
}
- (NSString *)dataFilePath {
return [[self documentsDirectory] stringByAppendingPathComponent:#"Checklists.plist"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
The file isn't created when -dataFilePath is called.
To write a plain string in your file, use:
NSError *e = nil;
[#"blabla" writeToFile:[self dataFilePath] atomically:YES encoding:NSUTF8StringEncoding error:&e];
NSError *e1 = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:[self dataFilePath] encoding:NSUTF8StringEncoding error:&e1];
Both errors should be nil and fileContents should contain the original string.

Save new plist file with filename equal to the value from a string variable

I am creating an iPhone application that will write the application data to a plist file, in which one of the text fields contains ProjName.text.
How can I save a plist file with the name of ProjName.text.plist.
For example, if the value of ProjName is "Servers" how do I save out of my array to a "Servers.plist" file?
This should work:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destination = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist", textfield.text];
[fileData writeToFile:destination atomically:YES];
[self savePlist:#"Servers" fromArray:yourArray]; //or
// [self savePlist:textField.text fromArray:yourArray];
#pragma mark - plist
- (NSString *) getFilePathForPlist:(NSString *) plistName {
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
}
-(void) savePlist:(NSString *)plistName fromArray:(NSMutableArray *)array {
[array writeToFile:[self getFilePathForPlist:plistName] atomically:YES];
}

Load a saved image from documents directory

I have used the code given here to save and load images
It works fine when i use it together in one view controller, but when i use the saveImage method in one view controller and try to load the image in another view controller the image returned blank...
In view controller A i use the following to save a image
- (void)saveImage: (UIImage*)image
{
NSLog(#"saveimage called");
if (image != nil)
{
NSLog(#"Image not null");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"test.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
QrImageView.image = nil;
}
}
And in view controller say B I'm loading the image using..
- (UIImage*)loadImage
{
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"test.png" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
// Write out the contents of home directory to console
NSLog(#"Documents directory: %#", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
return image;
}
I also get the content of the file in console but i dont understand why the image is blank
2013-07-06 14:13:19.750 YouBank[500:c07] Documents directory: (
"test.png"
)
Any idea what I'm doing wrong...
EDIT:
In the view controller B on the viewDidload method i do the following
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
ImageView.image=[self loadImage];
ImageName.text = #"Cash Withdrawal";
}
The problem is that you're updating your UIImageView with the UIImage only upon viewDidLoad. You need to add an update once you are done obtaining it from the filesystem (preferably on a background thread). So it would look something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
UIImage *loadedImage = [self loadImage];
dispatch_async(dispatch_get_main_queue(),^{
ImageView.image = loadedImage;
});
});
I would also recommend to use names starting with lowercase characters for instance names, so you should rename ImageView -> imageView
try this
//Document Directory
#define kAppDirectoryPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
#pragma mark - File Functions - Document/Cache Directory Functions
-(void)createDocumentDirectory:(NSString*)pStrDirectoryName
{
NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL];
}
-(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
{
NSString *strPath = #"";
if(pStrPathName)
strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];
return strPath;
}
When your write photo
[self createDocumentDirectory:#"MyPhotos"];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:strImageName];
[UIImagePNGRepresentation(imgBg.image) writeToFile:pngPath atomically:YES];
When you get the file
Edit
NSError *error = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[FunctionManager getDocumentDirectoryPath:#"MyPhotos"] error:&error];
if (!error) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self ENDSWITH '.png'"];
NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
for (int i=0;i<[imagesOnly count]; i++) {
[arrSaveImage addObject:[imagesOnly objectAtIndex:i]]; //arrSaveImage is Array of image that fetch one by one image and stored in the array
}
}
NSString *strPath=[self getDocumentDirectoryPath:#"MyPhotos"]; // "MyPhotos" is Your Directory name
strPath=[NSString stringWithFormat:#"%#/%#",strPath,[arrSaveImage objectAtIndex:i]]; //You can set your image name instead of [arrSaveImage objectAtIndex:i]
imgBackScroll.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:strPath]];
it may help you.

How do I load a CSV in IOS after saving it locally

I have a CSV file that I'm downloading from an S3 account and I would like to show it in my ios app by using the Quicklook framework.
The error I'm getting is in my console. It says
QLPreviewController's datasource shouldn't be nil at this point.
This appears after this line of code runs // Set data source
[previewer setDataSource:self];
here's all the code for downloading the file, saving it and then loading with quicklook
-(void)showDocument
{
NSString *stringURL = #"http://jornada.s3.amazonaws.com/Dust.csv";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:nil];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"tempfile.csv"];
//[urlData writeToFile:filePath atomically:YES];
BOOL newFile = [[NSFileManager defaultManager] createFileAtPath:filePath contents:urlData attributes:nil];
arrayOfDocuments = [[NSArray alloc] initWithObjects:
filePath, nil];
QLPreviewController *previewer = [[QLPreviewController alloc] init];
[self addSubview:previewer.view];
// Set data source
[previewer setDataSource:self];
// Which item to preview
[previewer setCurrentPreviewItemIndex:0];
}
}
/*---------------------------------------------------------------------------
*
*--------------------------------------------------------------------------*/
- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
return [arrayOfDocuments count];
}
/*---------------------------------------------------------------------------
*
*--------------------------------------------------------------------------*/
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
// Break the path into it's components (filename and extension)
NSArray *fileComponents = [[arrayOfDocuments objectAtIndex: index] componentsSeparatedByString:#"."];
NSArray *filePaths = [[fileComponents objectAtIndex:0] componentsSeparatedByString:#"/"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[((NSString *)[filePaths objectAtIndex:[filePaths count]-1]) stringByAppendingString:(NSString*)[fileComponents objectAtIndex:1]]];
// Use the filename (index 0) and the extension (index 1) to get path
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists) {
//
}
return [NSURL fileURLWithPath:filePath isDirectory:NO];
}
You don't add a preview controller's view to your view - you present the preview controller. And you should do that after setting the data source! So, in this order:
QLPreviewController* preview = [QLPreviewController new];
preview.dataSource = self;
[self presentViewController:preview animated:YES completion:nil];

Resources