2011-11-06 15 views
28

Bien,¿Cómo hacer un directorio iOS?

Tengo una aplicación de Cydia que necesito actualizar. Sé con las aplicaciones de Cydia que no tienen una carpeta de documentos, por lo que debes crear una. Y así es como lo hice antes en IOS 4 (que no funciona en iOS 5):

mkdir("/var/mobile/Library/APPNAME", 0755); 
mkdir("/var/mobile/Library/APPNAME/Documents", 0755); 

NSString *foofile = @"/var/mobile/Library/APPNAME/Documents/database.db"; 
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile]; 

if (fileExists == TRUE) { 
    NSLog(@"already exists"); 
} else { 
    NSLog(@"doesn't exists"); 
    NSFileManager *fileManager = [[NSFileManager defaultManager]autorelease]; 
    NSError *error; 
    NSString *documentDBFolderPath = @"/var/mobile/Library/APPNAME/Documents/database.db"; 

    NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.db"]; 
    [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error]; 

} 

También incluido código que copia el archivo de base de datos para esa carpeta, también. Eso no funciona (incluso cuando creo la carpeta manualmente a través de SSH).

Por favor ayuda! Gracias.

+0

¿Cuál es tu pregunta? –

+0

¿Qué está mal o qué otro código podría usar para crear directorios? – iosfreak

+0

Correcto, ¿qué está mal? No nos lo has dicho. No hay mensajes de error, no hay descripción de la falla. –

Respuesta

59

Aquí es el método que hice para crear directorios

-(void)createDirectory:(NSString *)directoryName atFilePath:(NSString *)filePath 
{ 
    NSString *filePathAndDirectory = [filePath stringByAppendingPathComponent:directoryName]; 
    NSError *error; 

    if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory 
            withIntermediateDirectories:NO 
                attributes:nil 
                 error:&error]) 
    { 
     NSLog(@"Create directory error: %@", error); 
    } 
} 
+0

Este es el error que recibo ... 'La operación no pudo completarse. Operación no permitida' – iosfreak

+2

Esto podría ser lo que buscas http://stackoverflow.com/questions/4650488/is-an-iphone-apps-document-directory-var-mobile-documents-or-var-mobile-libra – syclonefx

3

Verificar NSFileManager's class reference. Para crear carpetas, necesita createDirectoryAtPath:withIntermediateDirectories:attributes:error:

+0

Lo intenté y no se creó ninguna carpeta ... I ¿Crees que es solo para OSx, no para iOS? – iosfreak

+0

¿Ha utilizado 'SÍ' como argumento de' withInmediateDirectories: '? – Jef

+0

'NSFileManager * NSFm = [NSFileManager defaultManager]; [NSFm createDirectoryAtPath: @ "/ var/mobile/Library/APPNAME" withIntermediateDirectories: YES attributes: nil error: nil]; [NSFm createDirectoryAtPath: @ "/ var/mobile/Library/APPNAME/Documents" withIntermediateDirectories: YES attributes: nil error: nil]; 'fue el código exacto que utilicé ... – iosfreak

4

Pruebe usar createDirectoryAtURL:withIntermediateDirectories:attributes:error:.

NSFileManager Class Reference:

createDirectoryAtURL:withIntermediateDirectories:attributes:error:

Creates a directory with given attributes at the specified path.

Parameters

url - A file URL that specifies the directory to create. If you want to specify a relative path, you must set the current working directory before creating the corresponding NSURL object. This parameter must not be nil.

createIntermediates - If YES , this method creates any non-existent parent directories as part of creating the directory in url. If NO , this method fails if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.

attributes - The file attributes for the new directory and any newly created intermediate directories. You can set the owner and group numbers, file permissions, and modification date. If you specify nil for this parameter or omit a particular value, one or more default values are used as described in the discussion. For a list of keys you can include in this dictionary, see “Constants” (page 54) section lists the global constants used as keys in the attributes dictionary. Some of the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not apply to directories.

error - On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.

Return Value
YES if the directory was created or already exists or NO if an error occurred.

+0

Parece ser un poco lento cuando respondo desde mi iPad ..., la otra respuesta parece ser más o menos la misma. – chown

0

En Swift, devuelve verdadero si existe o creado.

func ensureDirectoryExists(path:String) -> Bool { 

    if !NSFileManager.defaultManager().fileExistsAtPath(path) { 
     do { 
      try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil) 
     } catch { 
      print(error) 
      return false 
     } 
    } 
    return true 
} 
Cuestiones relacionadas