Каталог документов NSDocument и просмотр коллекции изображений

#objective-c #uicollectionview #singleton #nsdocumentdirectory

#objective-c #uicollectionview #синглтон #Каталог документов nsdocument

Вопрос:

Я разрабатываю приложение, например, делаю снимок с камеры и сохраняю их в массиве словаря и в пути к каталогу nsdocument в одноэлементном классе. я показываю сохраненное изображение в представлении коллекции, соответствующем каждой ячейке. Я пробовал, но я получаю, что изображение представления коллекции показывает одно и то же изображение в каждой ячейке.

Например, количество массивов равно 2, для 2 ячеек отображается последнее изображение, то есть второе изображение.Поэтому, пожалуйста, помогите мне. Код показан ниже…

Класс CameraVC

// во время фотосъемки

 -(IBAction)takephoto:(id)sender
{
tapCount  = 1;
AVCaptureConnection *videoConnection  = nil;
for(AVCaptureConnection *connection in StillImageOutput.connections)
{
    for(AVCaptureInputPort *port in  [connection inputPorts])
    {
        if ([[port mediaType] isEqual:AVMediaTypeVideo]){
            videoConnection =connection;
            break;
        }}}

  [StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){

    if (imageDataSampleBuffer!=NULL) {
      NSData *imageData =[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];

       self.image = [ UIImage imageWithData:imageData];
        int x = arc4random() % 100;
        NSTimeInterval secondsSinceUnixEpoch = [[NSDate date]timeIntervalSince1970];

      ImageName = [NSString stringWithFormat:@"%@_%d_%d",self.siteName,x,(int)secondsSinceUnixEpoch];

      [[SingletonImage singletonImage]SaveImageInNSdocumentAndCache:self.image withImageName:ImageName];
     [self.collection_View reloadData];
 }
   }];}
  

МОИ методы просмотра коллекции

 -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[[SingletonImage singletonImage]arrayDict] count];}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

CollectionViewCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

//Loading images in collection view cell
Cell.image_View.image = [[SingletonImage singletonImage]ProvideImage:ImageName];

 return Cell;

  } 
  

Это мой одноэлементный класс

  #import "SingletonImage.h"
@implementation SingletonImage
- (id)init
{
self = [super init];
if ( self )
{
    self.arrayDict = [[NSMutableArray alloc] init];
   self.imageDict = [[NSMutableDictionary alloc]init];
  }
return self;}

 (instancetype)singletonImage
{
static SingletonImage *singletonImage;
static dispatch_once_t onceToken;
dispatch_once(amp;onceToken, ^{
    singletonImage = [[SingletonImage alloc]init];
    });
return singletonImage;}
  

// Сохранение изображения в массив словарей и путь к каталогу nsdocument

  -(void)SaveImageInNSdocumentAndCache:(UIImage *)image  withImageName:(NSString *)str
 {
//Saving image in array of dictionaries
[self.imageDict setObject:image forKey:str];
  [self.arrayDict insertObject:self.imageDict atIndex:0];
NSLog(@" array of dictionaries%@",self.arrayDict);
//Saving image in nsdocumnet directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths.firstObject;
NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageFolder = @"Photos";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyMMddHHmmss"];
   NSString *imagePath = [NSString stringWithFormat:@"%@/%@",documentDirectory,imageFolder];

BOOL isDir;
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:imagePath isDirectory:amp;isDir])
    if(![fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: folder creation failed %@", documentDirectory);

[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", imagePath, str] contents:nil attributes:nil];
[imageData writeToFile:[NSString stringWithFormat:@"%@/%@", imagePath, str] atomically:YES];}
  

//Укажите изображение, если оно есть в словаре, или укажите путь к каталогу nsdocument

    - (UIImage *)ProvideImage:(NSString *)text {

UIImage *Savedimage;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:text];
   if ([self.imageDict objectForKey:text])
   {
   Savedimage = [self.imageDict objectForKey:text];
    }
  else if([[NSFileManager defaultManager]fileExistsAtPath:filePath])
  {

    Savedimage = [UIImage imageWithContentsOfFile:filePath];

    NSLog(@"%@",Savedimage);

        NSLog(@"File exists at the path");  }
    else
      {
        NSLog(@"Image doesnot exist");
      }


NSLog(@" the saved image is :%@",Savedimage);
 return Savedimage;}
  

Файл VC.h
Здесь я объявил nsstring

    @interface CameraViewController : UIViewController<UICollectionViewDataSource ,UICollectionViewDelegate,UIImagePickerControllerDelegate>
 {   NSString *ImageName;

  }
  

и ImageName используется в ячейке для элемента в методе индексного пути, чтобы получить изображение из одноэлементного класса.
Я пробовал то, что знаю.

Комментарии:

1. Пожалуйста, кто-нибудь поможет мне сделать это

2. Убедитесь, что сохраненное изображение не перезаписано с тем же именем

3. @Jecky, я переопределяю его с тем же именем. Пожалуйста, дайте предложение, чтобы облегчить это

4. Используйте этот код для присвоения уникального имени. NSString *myUniqueName = [NSString stringWithFormat:@»%@-%u», @»YOURIMAGENAME», (NSUInteger)([[NSDate date] timeIntervalSince1970]*10.0)];

5. @Jecky, если я укажу локальную переменную, как указано выше, как я могу передать имя изображения в ячейке для элемента в пути индекса, чтобы получить изображение. Здесь ** Cell.image_View.image = [[SingletonImage singletonImage]ProvideImage:ImageName]; **