Сохранение и выборка нескольких выборок изображений из библиотеки в основных данных
Я строю проект, в котором я использую ELCImagepickerController для множественного выбора, а затем я сохраняю выбранное изображение в основные данные. Теперь я загружаю эти изображения в другой виртуальный канал и показываю их в UICollectionView.
Но проблема, с которой я здесь сталкиваюсь, заключается в том, что изображения не отображаются должным образом в collectionView. У меня два путаницы.
- Изображения правильно сохраняются в основных данных или нет.
- Если изображения сохранены, то правильно загружаются или нет.
Здесь я ввожу выбранные изображения в основные данные
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:@"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[objPhotos setPhotosInAlbum:self.imageData];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(@"Can't Save! %@ %@", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success!!" message:@"Photos Successfully Selected!" delegate:self cancelButtonTitle:@"DONE" otherButtonTitles:nil];
[alert show];
}
Здесь я выбираю эти выбранные изображения
-(NSArray *)getMenCategoryList
{
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *moc=app.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Albums" inManagedObjectContext:moc];
[fetch setEntity:entity];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];
if (!result) {
return nil;
}
return result;
}
Я вызываю функцию извлечения в - (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
и возвращая количество массивов
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self getMenCategoryList] count];
}
И, наконец, заполнение изображений в коллекцию.
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"albumCollectionViewCellCell" forIndexPath:indexPath];
Photos *objAlbumPhotos = (Photos *)[[self getMenCategoryList] objectAtIndex:indexPath.row];
UIImage *albumImg = [UIImage imageWithData:[objAlbumPhotos valueForKey:@"photosInAlbum"]];
UIImageView *photosimageview = (UIImageView *)[cell.contentView viewWithTag:1];
photosimageview.image = albumImg;
return cell;
}
Любая помощь высоко ценится.
1 ответ
ПРИМЕЧАНИЕ: я просто редактирую ваш код Пожалуйста, подтвердите сначала согласно вашему коду и отредактируйте согласно вашему требованию
Шаг 1: сгенерируйте уникальное имя файла и сохраните ваше изображение с этим именем в вашем пути к файлу.
шаг 2: после успешной записи вашего файла сохраните этот путь к вашим основным данным.
Шаг 3: для получения используйте путь к основным данным, чтобы получить изображения из каталога.
- (NSString*)generateFileNameWithExtension:(NSString *)extensionString {
// Extenstion string is like @".png"
NSDate *time = [NSDate date];
NSDateFormatter* df = [NSDateFormatter new];
[df setDateFormat:@"dd-MM-yyyy-hh-mm-ss"];
NSString *timeString = [df stringFromDate:time];
int r = arc4random() % 100;
int d = arc4random() % 100;
NSString *fileName = [NSString stringWithFormat:@"File-%@%d%d%@", timeString, r , d , extensionString ];
NSLog(@"FILE NAME %@", fileName);
return fileName;
}
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:@"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSString *strfilename = [self generateFileNameWithExtension:@".jpg"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:strfilename];
[_imageData writeToFile:filePath atomically:YES];
[objPhotos setPhotosInAlbum:filePath];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(@"Can't Save! %@ %@", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success!!" message:@"Photos Successfully Selected!" delegate:self cancelButtonTitle:@"DONE" otherButtonTitles:nil];
[alert show];
}