ios system to delete the file code

  • 2020-05-09 19:22:00
  • OfStack

Method 1: this objective c code is used to delete the file in the specified path


if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
   NSLog(@"Removed successfully");
 }

Method 2:


NSFileManager *defaultManager;
defaultManager = [NSFileManager defaultManager];

[defaultManager removeFileAtPath: tildeFilename
handler: nil];

handler can receive messages, such as fileManager:shouldProceedAfterError: if deletion fails.

Method 3:

IOS delete file delete folder create file create folder judge the file exists md5 wrapper class

I have been using the access and delete of data recently, so I wrote a class including functions, which is quite convenient for me to use

StorageData.m


//
// StorageData.m
// xunYi7
//
// Created by david on 13-6-28.
// Copyright (c) 2013 years  david. All rights reserved.
//

#import <CommonCrypto/CommonDigest.h>
#import "StorageData.h"
#import "xunYi7AppDelegate.h"

@implementation StorageData

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  NSLog(@" Start" didReceiveData Search data ");
}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  NSLog(@" Start" didReceiveResponse Search data ");
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  NSLog(@"didFailWithError");
}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
  NSLog(@"connectionDidFinishLoading");
}

+(NSMutableData *)remoteFetchData:(NSString *)dataUrl{
  NSString *currentDataFilePath = [[self dataPath] stringByAppendingPathComponent:[self fetchTodayDate]];
  
  // Create a directory 
  currentDataFilePath = [self createDirectory:currentDataFilePath];
  
  currentDataFilePath = [currentDataFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[self md5:dataUrl]]];
  
  if([xunYi7AppDelegate isReachable]){
    NSURL *url = [[NSURL alloc] initWithString:dataUrl];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                         timeoutInterval:60];
    
    NSURLResponse *response = [[NSURLResponse alloc] init];
    NSError *receiveDataError = [[NSError alloc] init];
    
    NSMutableData *receivedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:request
                                       returningResponse:&response
                                             error:&receiveDataError];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    return receivedData;
  }else{
    [xunYi7AppDelegate showNetworkMessage];
  }

  return nil;
}

+(NSMutableData *)localFetchData:(NSString *)dataUrl{
  
  NSString *currentDataFilePath = [[self dataPath] stringByAppendingPathComponent:[self fetchTodayDate]];
  NSString *yesterdayDataFilePath = [[self dataPath] stringByAppendingPathComponent:[self fetchYesterdayDate]];
  
  // Create a directory 
  currentDataFilePath = [self createDirectory:currentDataFilePath];
  
  currentDataFilePath = [currentDataFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[self md5:dataUrl]]];
  yesterdayDataFilePath = [yesterdayDataFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[self md5:dataUrl]]];
  
  NSMutableData *localData = [self fromFilenamePathFetchLocalData:currentDataFilePath];
  
  if(localData != nil){// The local data 
    return localData;
    
  }else{// Remote acquisition of data 
    
    NSMutableData *receivedData = [self remoteFetchData:dataUrl];
    
    if(receivedData != nil){
      if([self storageDataToFile:receivedData fileName:currentDataFilePath]){
        NSLog(@" Save success ");
        [self removeDirectory];
      }else{
        NSLog(@" Save failed ");
      }
    }else{
      if((localData = [self fromFilenamePathFetchLocalData:yesterdayDataFilePath]) != nil){
        return localData;
      }
    }
    return receivedData;
  }
  return nil;
}

//md5 Encrypted string 
+(NSString *)md5:(NSString *)str{
  const char *cStr = [str UTF8String];
  unsigned char result[16];
  CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
  return [NSString stringWithFormat:
      @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
      result[0], result[1], result[2], result[3],
      result[4], result[5], result[6], result[7],
      result[8], result[9], result[10], result[11],
      result[12], result[13], result[14], result[15]
      ]; 
}
// Upload image storage 
+(void) saveUploadImage:(UIImage *)image withName:(NSString *)imageName{
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  NSError *error;
  
  //  Get the sandbox directory 
  NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
  fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
  if(![fileManager fileExistsAtPath:fullPath]){
    [fileManager createDirectoryAtPath:fullPath
        withIntermediateDirectories:YES
                attributes:nil
                   error:&error];
  }
  
  fullPath = [fullPath stringByAppendingPathComponent:imageName];
  NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
  
  //  Write the image to a file 
  [imageData writeToFile:fullPath atomically:NO];
}

// Upload image delete 
+(void) removeUploadImage:(UIImage *)image withName:(NSString *)imageName{
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  NSError *error;
  
  //  Get the sandbox directory 
  NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
  fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
  if(![fileManager fileExistsAtPath:fullPath]){
    [fileManager removeItemAtPath:fullPath error:&error];
  }
}

// Gets the stored image 
+(NSString *)fetchUploadImagePath:(NSString *)imageName{
  NSString *fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
  fullPath = [fullPath stringByAppendingPathComponent:@"tmpImage"];
  fullPath = [fullPath stringByAppendingPathComponent:imageName];
  return fullPath;
}

// Determine if the file exists 
+(NSString *)isFileExists:(NSString *)fullpath{
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  if([fileManager fileExistsAtPath:fullpath]){
    return fullpath;
  }
  return nil;
}

// Data is stored 
//+(void)

// Gets the directory where the files are stored 
+(NSString *)dataPath{
  // The image access path is first specified here (written to the application sandbox by default)   C) 
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
  
  // And give the file a name 
  NSString *filePathDerectory = [paths objectAtIndex:0];
  
  return filePathDerectory;
}

// Gets the data for the specified file 
+(NSMutableData *)fromFilenamePathFetchLocalData:(NSString *)filename{
  // Saves the data to the specified file 
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  if([fileManager fileExistsAtPath:filename]){
    NSData *data = [fileManager contentsAtPath:filename];
    return [data mutableCopy];
  }
  
  return nil;
}

// Stores data to the specified file 
+(BOOL) storageDataToFile:(NSData *)data fileName:(NSString *)fileName{
  // Saves the data to the specified file 
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  if([fileManager createFileAtPath:fileName contents:data attributes:nil]){
    return YES;
  }else{
    return NO;
  }
}

// Delete the file 
+(void) deleteFile:(NSString *)fileName{
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  NSError *error;
  [fileManager removeItemAtPath:fileName error:&error];
}

// Get today's date 
+(NSString *) fetchTodayDate{
  NSDate *currentDate = [NSDate date];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
  return [dateFormatter stringFromDate:currentDate];
}

// Get yesterday's date 
+(NSString *) fetchYesterdayDate{
  NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-(24 * 60 * 60)];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
  return [dateFormatter stringFromDate:yesterdayDate];
}

// Get the date of the day before yesterday 
+(NSString *) fetchYesterdayBeforeDate{
  NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-(2 * (24 * 60 * 60))];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
  return [dateFormatter stringFromDate:yesterdayDate];
}

// Gets the data that stores the file 

// Create a file 

// Create a directory 
+(NSString *) createDirectory:(NSString *)directoryName{
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  NSError *error;
  if(![fileManager fileExistsAtPath:directoryName]){
    [fileManager createDirectoryAtPath:directoryName
        withIntermediateDirectories:YES
                attributes:nil
                   error:&error];
    if(error == nil){
      return directoryName;
    }else{
      return directoryName;
    }
  }else{
    return directoryName;
  }
}
// Delete the file 
+(void) removeFile:(NSString *)filePath{
  NSError *error;
  
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  if([fileManager fileExistsAtPath:filePath]){
    [fileManager removeItemAtPath:filePath error:&error];
  }
  if(error){
    NSLog(@"error = %@",error);
  }
}

// Delete the directory 
+(void) removeDirectory{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsPath = [paths objectAtIndex:0];
  NSString *removeDirectoryPath = [documentsPath stringByAppendingPathComponent:[self fetchYesterdayBeforeDate]];
  NSError *error;
  
  NSFileManager *fileManager = [[NSFileManager alloc] init];
  if([fileManager fileExistsAtPath:removeDirectoryPath]){
    [fileManager removeItemAtPath:removeDirectoryPath error:&error];
  }
  if(error){
    NSLog(@"error = %@",error);
  }
}
@end
StorageData.h

//
// StorageData.h
// xunYi7
//
// Created by david on 13-6-28.
// Copyright (c) 2013 years  david. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface StorageData : NSObject<NSURLConnectionDataDelegate, NSURLConnectionDelegate>

+(NSMutableData *)remoteFetchData:(NSString *)dataUrl;
+(NSMutableData *)localFetchData:(NSString *)dataUrl;
+(void) saveUploadImage:(UIImage *)image withName:(NSString *)imageName;
+(NSString *) uploadImage:(UIImage *)image withName:(NSString *)imageName;
+(NSString *) fetchUploadImagePath;
+(NSString *) fetchUploadImagePath:(NSString *)imageName;
+(void) removeUploadImage:(UIImage *)image withName:(NSString *)imageName;
+(NSString *)isFileExists:(NSString *)fullpath;
+(void) removeFile:(NSString *)filePath;
@end

There are imperfections, I hope to correct and modify


Related articles: