2016-11-28 11 views
0

Я хочу хранить файлы пользователя внутри папок в каталоге путей. Как хранить файлы и извлекать их по мере необходимости? БлагодаряСделать каталог в моем приложении для хранения файлов разных типов

+1

4 upvotes для вопроса, у которого есть тонны ответов онлайн .. шокирован ... –

ответ

1
#pragma mark -- list all the files exists in Document Folder in our Sandbox. 
// Fetch directory path of document for local application. 
- (void)listAllLocalFiles{ 

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

    NSFileManager *manager = [NSFileManager defaultManager]; 
    // This function will return all of the files' Name as an array of NSString. 
    NSArray *files = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
    // Log the Path of document directory. 
    NSLog(@"Directory: %@", documentsDirectory); 
// For each file, log the name of it. 
    for (NSString *file in files) { 
     NSLog(@"File at: %@", file); 
    } 
} 

#pragma mark -- Create a File in the Document Folder. 
- (void)createFileWithName:(NSString *)fileName{ 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

     NSFileManager *manager = [NSFileManager defaultManager]; 
     // 1st, This funcion could allow you to create a file with initial contents. 
     // 2nd, You could specify the attributes of values for the owner, group, and permissions. 
     // Here we use nil, which means we use default values for these attibutes. 
     // 3rd, it will return YES if NSFileManager create it successfully or it exists already. 
     if ([manager createFileAtPath:filePath contents:nil attributes:nil]) { 
       NSLog(@"Created the File Successfully."); 
     } else { 
       NSLog(@"Failed to Create the File"); 
     } 
} 


#pragma mark -- Delete a File in the Document Folder. 
- (void)deleteFileWithName:(NSString *)fileName{ 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     // Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator. 
     NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

     NSFileManager *manager = [NSFileManager defaultManager]; 
     // Need to check if the to be deleted file exists. 
     if ([manager fileExistsAtPath:filePath]) { 
      NSError *error = nil; 
      // This function also returnsYES if the item was removed successfully or if path was nil. 
      // Returns NO if an error occurred. 
      [manager removeItemAtPath:filePath error:&error]; 
      if (error) { 
        NSLog(@"There is an Error: %@", error); 
      } 
     } else { 
      NSLog(@"File %@ doesn't exists", fileName); 
     } 
    } 

    #pragma mark -- Rename a File in the Document Folder. 
    - (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName{ 
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName]; 
     NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName]; 
     NSFileManager *manager = [NSFileManager defaultManager]; 
       if ([manager fileExistsAtPath:filePathSrc]) { 
        NSError *error = nil; 
        [manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error]; 
        if (error) { 
         NSLog(@"There is an Error: %@", error); 
        } 
       } else { 
        NSLog(@"File %@ doesn't exists", srcName); 
      } 
    } 

#pragma mark -- Read a File in the Document Folder. 
    /* This function read content from the file named fileName. 
    */ 
- (void)readFileWithName:(NSString *)fileName{ 
     // Fetch directory path of document for local application. 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     // Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator. 
     NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

     // NSFileManager is the manager organize all the files on device. 
     NSFileManager *manager = [NSFileManager defaultManager]; 
     if ([manager fileExistsAtPath:filePath]) { 
       // Start to Read. 
       NSError *error = nil; 
       NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:&error]; 
       NSLog(@"File Content: %@", content); 

       if (error) { 
        NSLog(@"There is an Error: %@", error); 
       } 
      } else { 
       NSLog(@"File %@ doesn't exists", fileName); 
      } 
    } 
1

Вы можете управлять, как,

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

NSString *documentsDirectoryForSaveImages = [docsDir stringByAppendingPathComponent:@"/ProfileImages"]; 

// this will create "ProfileImages" directory in document directory 

[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectoryForSaveImages withIntermediateDirectories:YES attributes:nil error:nil]; 

NSString *profilePicturePath = [documentsDirectoryForSaveImages stringByAppendingPathComponent:@"profilePicture"]; 

Теперь предположим, что у вас есть image, что вы хотите сохранить затем конвертировать в данных, и вы можете записать его на пути, как

NSData *data = UIImageJPEGRepresentation(yourImage, 1.0); 

    [data writeToFile:profilePicturePath atomically:NO]; 

вы можете использовать или получить это изображение нравится,

self.imageViewProfile.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:profilePicturePath]]; // here "imageViewProfile" is UIImageView! 

Аналогичным образом, вы можете хранить различные виды f ile путем преобразования его в NSData в каталог!

1

Создать папку и сохраните файл:

NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsDirectory = [paths objectAtIndex:0]; 
NSString *dataPath = [docsDirectory stringByAppendingPathComponent:@"/MyDirectory"]; 

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) { 
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Creating folder 
} 
NSString *filePath = [dataPath stringByAppendingPathComponent:@"MyFile.txt"]; 
NSString *content = @"My content"; 
    [content writeToFile:fileName 
         atomically:NO 
           encoding:NSStringEncodingConversionAllowLossy 
             error:nil]; 

Это создаст имена папок "MyDirectory" в каталоге документов и файл с именем "MyFile.txt" с содержанием в нем "My content"

Теперь пишу этот кусок кода получить список файлов из вашего каталога,

NSString * resourcePath = [[NSBundle mainBundle] resourcePath]; 
NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"MyDirectory"]; 
NSError * error; 
NSArray * arrayMyDirectoryList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error]; 

Таким образом, "arrayMyDirectoryList" будет списком всех документов, сохраненных в каталоге.