Jonathan
Jonathan

Reputation: 614

Saving and then Deleting files from documents directory in iOS

I'm able to save and delete files from my iOS documents directory, however, I'm running into a bug where after I delete from there I'm unable to save a new file. Can someone please explain why it is doing that?

- (IBAction)saveInfo:(id)sender {

//int x = 0;
//if (x == 0) { // for testing without field checking
if([self checkFields]){

NSString *resultLine;
// save all data to string using csv formatting
    if (isClassProject) {
        //NSString *waypointText = self.Waypoints.text;
        resultLine=[NSString stringWithFormat:@"Name,Partner,Temperature,Weather,Project,Instructor/Mentor,Class,Waypoints/Trackers,Notes\n%@,%@,%@,%@,%@,%@,%@,%@,%@\n",
                    [[self YourName] text], [[self PartnersName] text], [[self CurrentTemp] text],
                    [[self CurrentWeather] text], [[self ProjectName] text], [[self InstructorName] text],
                    [[self ClassNum] text], [[self Waypoints] text], [[self Notes] text]];
        //NSLog(@"%@",[[self YourName] text]);
        NSLog(@"%@",resultLine);
    }
    else{
        resultLine=[NSString stringWithFormat:@"Name,Partner,Temperature,Weather,Project,Instructor/Mentor,Waypoints/Trackers,Notes\n%@,%@,%@,%@,%@,%@,%@,%@\n",
                    [[self YourName] text], [[self PartnersName] text], [[self CurrentTemp] text],
                    [[self CurrentWeather] text], [[self ProjectName] text], [[self InstructorName] text],
                    [[self Waypoints] text], [[self Notes] text]];
        NSLog(@"%@",resultLine);
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // get today's date for file name
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    NSString *todayDate = [dateFormatter stringFromDate:today];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/%@_%@_%@.csv",documentsDirectory,
                          todayDate,[[self ProjectName] text],[[self YourName] text]];
    //create content - four lines of text
    //NSString *content = @"One\nTwo\nThree\nFour\nFive";
    //save content to the documents directory
    [resultLine writeToFile:fileName
              atomically:NO
                encoding:NSUTF8StringEncoding
                   error:nil];

    // now empty fields
    /*
    self.YourName.text =@"";
    self.PartnersName.text =@"";
    self.CurrentTemp.text =@"";
    self.CurrentWeather.text =@"";
    self.ProjectName.text =@"";
    self.InstructorName.text =@"";
    self.ClassNum.text =@"";
    self.Waypoints.text =@"";
    self.Notes.text =@"";*/
    //NSLog(@"Data Saved"); //for Xcode command line

}

- (IBAction)deleteAllFiles:(id)sender {
// set path to documents dir
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// if files exist then delete
 if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]) {
    NSFileManager *manager = [NSFileManager defaultManager];
     NSLog(@"Found Files in documentsDirectory");
     NSError *error = nil;
     [manager removeItemAtPath:documentsDirectory error:&error];

    if (error){
        NSLog(@"There is an Error: %@", error);
    } else{
        NSLog(@"No files");
    }
}

Upvotes: 0

Views: 1537

Answers (3)

Jonathan
Jonathan

Reputation: 614

I ended up solving it with the following code:

- (IBAction)deleteAllFiles:(id)sender {

NSString *csvFile = @"csv";
NSString *jpgFile = @"jpg";
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
// if files exist then delete
NSArray *contents = [[NSFileManager defaultManager]
                     contentsOfDirectoryAtPath: documentsDirectory error:&error];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;

while ((filename = [e nextObject])) {

    if ([[filename pathExtension] isEqualToString:csvFile]) {
        [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
    }
    if ([[filename pathExtension] isEqualToString:jpgFile]) {
        [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
    }
}

}

I found another example on stackoverflow that allows you to use the file extensions. That worked perfectly for me since I am only saving jpg and csv files to the sandbox.

Upvotes: 1

nmh
nmh

Reputation: 2503

Is there a way to delete them all at once?

You can delete like you do before. It means delete Document folder and it's files.

But when you create new file, you have to check whether Document folder is existed or not. If not, create Document folder:

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:documentsDirectory]){
  // if Document folder is not existed, create it. 
  [ createFileAtPath:documentsDirectory contents:nil attributes:nil];
}
.... // do with your files

Upvotes: 0

Andy
Andy

Reputation: 14302

The reason you cannot save a new file to that directory after calling your delete method is because the directory no longer exists.

Instead of deleting the entire Documents directory, just delete the contents of that directory.

For example:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: documentsDirectory error:&error]
if (error) {
     // Handle error
}
else {
    for (NSString *filename in ) {
        if (![[NSFileManager defaultManager] removeItemAtPath:filename error:&error];
            // Handle error
       }
    }
}

Upvotes: 0

Related Questions