2011-01-25 16 views

Respuesta

94
NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease]; 
NSError *error = nil; 
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]; 
if (error == nil) { 
    for (NSString *path in directoryContents) { 
     NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path]; 
     BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error]; 
     if (!removeSuccess) { 
      // Error handling 
      ... 
     } 
    } 
} else { 
    // Error handling 
    ... 
} 
+1

funcionó en su mayor parte. pero resulta que removeItemAtPath requiere una ruta de archivo completa. así que usé este NSString * myFilePath = [documentsDir stringByAppendingPathComponent: ruta]; gracias. –

+1

Así es, Jinah. Mi error. Voy a corregir el código de arriba. –

+2

Si esto funciona, sería bueno eliminar el comentario 'Código no probado:'. Gracias – Warpspace

6
- (void)removeFile 
{ 
    // you need to write a function to get to that directory 
    NSString *filePath = [self getDirectory]; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:filePath]) 
    { 
     NSError *error; 
     if (![fileManager removeItemAtPath:filePath error:&error]) 
     { 
      NSLog(@"Error removing file: %@", error); 
     }; 
    } 
} 

Creo que esto es más corto.

+0

Parece que esto solo elimina un único archivo o directorio – Warpspace

15

El código no funcionaba con IOS 7 y Xcode 5, por lo que se editó para que funcione con mi aplicación. Grandes créditos para @Ole Begemann y @pablasso.

-(void)EmptySandbox 
{ 
    NSFileManager *fileMgr = [[NSFileManager alloc] init]; 
    NSError *error = nil; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil]; 

    while (files.count > 0) { 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]; 
     if (error == nil) { 
      for (NSString *path in directoryContents) { 
       NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path]; 
       BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error]; 
       files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
       if (!removeSuccess) { 
        // Error 
       } 
      } 
     } else { 
      // Error 
     } 
    } 
} 
+0

Si está utilizando CoreData, solo tenga en cuenta que esto eliminará su Modelo también – BenB

+0

Gracias, este código funciona como un amuleto. Soy un novato y sucede que sobrescribo el archivo almacenado NSMutableArray con NSMutableDictionary en el iPad. Guardar mi vida – nuttynibbles

2
NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease]; 
NSError *error = nil; 
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]; 
if (error == nil) { 
    for (NSString *path in directoryContents) { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path]; 
    BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error]; 
    if (!removeSuccess) { 
     // Error handling 
     ... 
    } 
} 
} else { 
// Error handling 
... 
} 
2

puede no ser aplicable en todos los casos, pero en general sería más eficiente para poner todos los archivos en un directorio personalizado dentro de Documentos Directorio y luego usar removeItemAtPath:error: eliminar ese directorio y crear de nuevo. Por ejemplo:

// Clear cache 
NSError *error; 
[[NSFileManager defaultManager] removeItemAtPath:cacheDirectory error:&error]; 
if (error) 
{ 
    // error handling 
} 

// Create cache directory again 
NSError *error2; 
[[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&error2]; 
if (error2) 
{ 
    // error handling 
} 
15

Para desarrolladores Swift:

let fileMgr = NSFileManager() 
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
if let directoryContents = try? fileMgr.contentsOfDirectoryAtPath(dirPath) 
{ 
    for path in directoryContents 
    { 
     let fullPath = (dirPath as NSString).stringByAppendingPathComponent(path) 
     do 
     { 
      try fileMgr.removeItem(atPath: fullPath) 
      print("Files deleted") 
     } 
     catch let error as NSError 
     { 
      print("Error deleting: \(error.localizedDescription)") 
     } 
    } 
} 
5

Swift 2.1 con un poco de sobrepeso de:

do { 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
    let documentsDirectory = paths[0] 
    let documentsDirectoryURL = NSURL(fileURLWithPath: paths[0]) 

    let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentsDirectory) 

    var totalMegaBytes: Double = 0 
    var nrOfFiles = 0 

    for filename in directoryContents { 
     let file = documentsDirectoryURL.URLByAppendingPathComponent(filename) 


     let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(file.path!) 
     let fileSize = fileAttributes[NSFileSize] as! Double    
     totalMegaBytes += fileSize/1024/1024 

     do { 
      try NSFileManager.defaultManager().removeItemAtURL(file) 
      nrOfFiles++ 
     }catch let error as NSError{ 
      print("> Emptying sandbox: could not delete file", filename, error) 
     } 
    } 

    print("> Emptying sandbox: Removed \(nrOfFiles) files with a total of \(round(totalMegaBytes))MB") 

}catch let error as NSError{ 
    print("> Emptying sandbox: Error emptying sandbox", error) 
} 
+0

obtengo "error arrojado desde aquí no se manejan porque la captura adjunta no es exhaustiva" – Luda

+0

Te estoy votando. Pero realmente deberías considerar eliminar esto: "deja error como NSError". O tal vez tenga alguna otra solución para el error anterior – Luda

+1

No entiendo esa advertencia. ¿No es NSError lo más exhaustivo posible? – Sam

Cuestiones relacionadas