In my app I download a pdf file with an ASiHttpRequest and I have these instructions:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[currentDownload setDownloadDestinationPath:[documentsDirectory stringByAppendingPathComponent:#"file.pdf"]];
it work fine at first time, and I can open this file.pdf, but when I download a second time this pdf, it seems that it not replace the file but do a merge.
before I do this, but it doesn't work where is the problem, or what's the best way to delete this file.pdf from its path?
- (void) removeFile{
NSString *extension = #"pdf";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPDF = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectoryPDF error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectoryPDF stringByAppendingPathComponent:filename] error:NULL];
}
}
}
EDIT
now I use this method
- (void) removeFile{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0]stringByAppendingString:#"/file.pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
if([fileManager fileExistsAtPath:path] == YES)
{
NSLog(#"file exist and I delete it");
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:path error:&error];
NSLog(#"error:%#", error);
}
NSLog(#"Documents directory after: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
}
this method recognize that in directory there is "file.pdf" in NSLog
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
but it crash after
"NSLog(#"file exist and I delete it");"
and I have only a "lldb" in consolle.
I use this method to delete pdf files from a local cache, with a few modifications you can adapt it to your necessities
- (void)removePDFFiles
{
NSFileManager *fileMngr = [NSFileManager defaultManager];
NSArray *cacheFiles = [fileMngr contentsOfDirectoryAtPath:[self cacheDirectory]
error:nil];
for (NSString *filename in cacheFiles) {
if ([[[filename pathExtension] lowercaseString] isEqualToString:#"pdf"]) {
[fileMngr removeItemAtPath:[NSString stringWithFormat:#"%#/%#", [self cacheDirectory], filename] error:nil];
}
}
}
Most probably you don't remove the file before downloading a new one and ASIHttpRequest sees that there's already a file with the same name and appends data to it instead of replacing the file. I'm not sure about the PDF format, but that shouldn't normally result in a merged readable file. In any case, first you need to use the error mechanism that the filemanager class offers you. Is bad to pass NULL. Very bad. So, create a NSError object and pass it to the contentsOfDirectoryAtPath and removeItemAtPath methods, then check the error, be sure the operations are done successfully. After that, you may want to check the extension upper case as well, as Unix based systems are case sensitive (although the simulator is not, the device is) and a example.PDF file will not get deleted based on your code.
Try the following:
-(BOOL) removePDF
{
BOOL removeStatus = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString* fileName = #"file.pdf"; //your file here..
NSString* filePath = [NSString stringWithFormat:#"%#/%#", docsDir, fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES)
{
removeStatus = [[NSFileManager defaultManager] removeItemAtPath:filePath];
}
return removeStatus;
}
Related
I am creating a directory inside my application.Is there a code to view the contents of the directory in xcode. For example in android you can create a custom directory and view its contents using a file manager application. Can the similar procedure be done in apple?
Here is the code which i use to create a directory?
bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
fileManager = [NSFileManager defaultManager];
myImageDirectory = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
if ([myImageDirectory count] == 1){
NSLog(#"myImageDirectoryIs already present directory is already present");
}else{
directoryPath = [[myImageDirectory objectAtIndex:0] URLByAppendingPathComponent:bundleIdentifier];
NSLog(#"myImageDirectory directory name = %#",[directoryPath absoluteString]);
NSError *theError = nil;
if (![fileManager createDirectoryAtURL:directoryPath withIntermediateDirectories:NO attributes:nil error:&theError]){
NSLog(#"didnt write image data");
}else{
imagePath = [[directoryPath absoluteString] stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#_%#_%#_image.jpg",dIdNo,iIdNo,[self currentDateandTime]]];
[imageData writeToFile:imagePath atomically:YES];
}
}
If your app is running in the simulator you'll need to use Finder. Go to the following directory:
/Users/<username>/Library/Application Support/iPhone Simulator/<iOS version>/Applications/<uuid>/Library/Application Support
If your app is running on the device you can use Xcode:
Connect the device
Choose menu option Window -> Organizer
Go to the Devices Tab
Click Applications under the device menu on the left
Pick your Application
The directory contents will be listed and you can optionally download everything.
try this...
to create a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
to retrieve contents from directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *customDirectory = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:customDirectory error:&error];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",customDirectory,strFile];
if([[strVideoPath pathExtension] isEqualToString:#"mp4"] || [[strVideoPath pathExtension] isEqualToString:#"mov"])
{
[urlArray addObject:strVideoPath];
}
}
you can get the contents of the directory(MYNewFolder) from below code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"MYNewFolder"];
NSArray *filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:stringPath
error:nil];
for ( NSString *apath in filePathsArray )
{
NSLog(#"inside the file path array=%d",apath);
}
Method
-(NSArray *) getObjectsInDirectory:(NSString *)directory {
NSFileManager * fm = [NSFileManager defaultManager];
NSError * error = nil;
NSArray * result = [fm contentsOfDirectoryAtPath:directory error:&error];
return result;
}
How-To
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray * files = [self getobjectsInDirectory:documentsPath];
This code is used to get an array of the files within the documents directory.
Viewing the Files
NSLog(#"%#", files);
Check this class out, it allows you to simplify so many things in iOS: Atomic Class
I have created a myDB.sqlite database from SQLite Manager firefox addon. I want to add this myDB.sqlite file to my project. Then I can write functions to get data from tables.
I tried to add the myDB.sqlite file to project folder & create a filepath like this. But I think this filepath is wrong.
-(NSString *) filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"document.sqlite"];
return path;
}
Does it correct to add myDB.sqlite file to the project folder? or where should I save this myDB.sqlite file & what is the filepath I should use?
add your myDB.sqlite file in your project. by right click your project name=> add files to ""projectName", then add it.
to get your file path you can add this in your appDelegate
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(#"dbpath : %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"myDB.sqlite"];
}
in your did finish with launching method call [self copyDatabaseIfNeeded];
I assume you have successfully copied sqlite db into project's folder. So you have sqlite Database in your app's bundle now.
So you need to copy database from app's bundle to document directory of device/simulator using following code. Write these in AppDelegate.m
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
// First, test for existence.
if (![fileManager fileExistsAtPath:folderPath])
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
NSString *dbPath = [folderPath stringByAppendingPathComponent:#"document.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"document.sqlite : Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/** Database copy is not exist **/
[self copyDatabaseIfNeeded];
// Override point for customization after application launch.
return YES;
}
-(void)addSqlFileIfNotExists {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:#"document.sqlite"];
BOOL exits = [fileManager fileExistsAtPath:writableDBPath];
if(exits) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"document.sqlite"];
BOOL exit = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if(!exit)
NSLog(#"%#",[error localizedDescription]);
}
I'm writing an app that needs to store some persistence information in file but i'm having trouble debugging the createFileAtPath:contents:attributes: function of NSFileManager, i have reduced the problem to the below piece of code.
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSString * fileName = #"newfile.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: fileName];
NSLog(#"full path name: %#", filePath);
// check if file exists
if ([filemgr fileExistsAtPath: filePath] == YES){
NSLog(#"File exists");
}else {
NSLog (#"File not found, file will be created");
if (![filemgr createFileAtPath:filePath contents:nil attributes:nil]){
NSLog(#"Create file returned NO");
}
}
Since the function doesn't take an NSError object i'm having trouble finding out why exactly it is returning false.
From other examples i have seen here Write a file on iOS and here How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device? it should be ok to pass nil to both the contents and attributes parameters. I've tried specifying both parameters and receive the same result.
I'm thinking this may be a permissions issue but i'm unsure if the below code is the correct way to check permissions on a directory.
if ([filemgr isWritableFileAtPath:documentsDirectory] == YES){
NSLog (#"File is readable and writable");
}
// Following Code will create Directory in DocumentsDirectory
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dirName = [docDir stringByAppendingPathComponent:#"MyDir"];
BOOL isDir
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dirName isDirectory:&isDir])
{
if([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil])
NSLog(#"Directory Created");
else
NSLog(#"Directory Creation Failed");
}
else
NSLog(#"Directory Already Exist");
swift5
guard let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
preconditionFailure()
}
let path = (docdir as NSString).appendingPathComponent(yourfilename + "." + yourfilenameExtension)
Im trying to create an folder in user library directory,but its not creating. Is there any mistake in the below code.
databaseName = #"KITSMAW0051_DB.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
databasePath = [[documentsDir stringByAppendingPathComponent:folder ] stringByAppendingPathComponent:databaseName];
Ok first of all databasePath describes a path to a file not a directory. But let's say you actually want to create "Swasstik" folder inside user's Library:
// Your code
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
// I edited here to keep only the folder
NSString *folderPath = [documentsDir stringByAppendingPathComponent:folder];
// At this point we got the path to the folder
// but we want to actually go on and create it
// NSFileManager to the rescue!
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath: folderPath
withIntermediateDirectories: NO
attributes: nil
error: nil];
Of course you can study and set the manager as you like and also implement some error handling. I hope that this makes sense...
databaseName = #"KITSMAW0051_DB.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = [documentsDir stringByAppendingPathComponent:#"Swasstik"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]) {
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error != nil) {
NSLog(#"Some error: %#", error);
return;
}
NSString *databasePath = [folder stringByAppendingPathComponent:databaseName];
I'm trying to move all of the documents that reside in the NSDocumentDirectory to the NSCachesDirectory, and then delete all of those NSDocument files upon the first app launch of my next version update to my app. The only reason I'm doing this is to abide by Apple's iOS data storage guidelines, as my app update was rejected for saving .PDF files to the NSDocumentsDirectory (I have no clue why, because the app has never been rejected for this until this update (app is almost 2 years old, and I have been saving .PDFs this way since day 1), maybe I got a strict reviewer?)
I need to move all of the user's already downloaded .PDF files to the NSCachesDirectory and then delete them from the NSDocumentDirectory.
Is there a simple way this can be accomplished?
Thank you in advance for any help provided.
I tried this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSUserDefaults *Defaults;
int launchCount;
Defaults = [NSUserDefaults standardUserDefaults];
launchCount = [Defaults integerForKey:#"launchCount" ] + 1;
[Defaults setInteger:launchCount forKey:#"launchCount"];
[Defaults synchronize];
if(launchCount == 1) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *dest = [path2 objectAtIndex:0];
NSArray *Contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error];
for(NSString *source in Contents)
{
if(![fileManager moveItemAtPath:source
toPath:dest
error:&error])
{
//TODO: Handle error
NSLog(#"Error: %#", error);
}
}
}
But I'm getting this error in the console:
NSFilePath=Test.pdf, NSDestinationFilePath=/Users/Charley/Library/Application Support/iPhone Simulator/5.1/Applications/96EB01D1-81B7-4ECE-B337-D2D663969EE3/Library/Caches, NSUnderlyingError=0xb566d50 "The operation couldn’t be completed. File exists"
Yes, use NSFileManager:
Get your documents path, and your caches path. Iterate over all the file, and move them using NSFileManager
- (void) moveAllDocs {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *sourceDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *destinationDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:sourceDirectory error:&error];
for(NSString *sourceFileName in contents) {
NSString *sourceFile = [sourceDirectory stringByAppendingPathComponent:sourceFileName];
NSString *destFile = [destinationDirectory stringByAppendingPathComponent:sourceFileName];
if(![fileManager moveItemAtPath:sourceFile toPath:destFile error:&error]) {
NSLog(#"Error: %#", error);
}
}
}