Populating Collection View from Array in Document Directory
You are iterating the directoryContents
for imageURL in directoryContents where imageURL.pathExtension == "jpeg" {
if let image = UIImage(contentsOfFile: imageURL.path) {
cell.myImageView.image = image //[indexPath.row] **need "image" to be an array so can assign to indexPath.row
} else {
fatalError("Can't create image from file \(imageURL)")
}
}
that's why you only get the last image on all the cells.
What you should do is fetch the directory contents and store it in an array variable (e.g. directoryContentsArray = self.fetchDirectoryContents())
make a function similar to this, and call it on viewDidLoad:
this will populate your array.
func fetchDirectoryContents() {
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
self.directoryContentsArray = directoryContents
self.tableView.reloadData()
}
Then use the array count for numberOfRows and for the datasource as well.
your current design is actually bad right now since you're always calling for FileManager in all your tableView methods
Now, after adding an image successfully and saving it, you will repopulate your array (or you can actually just append it to your existing array)
EDIT: So in your cellForItem
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? myCell {
let imageFile = self.directoryContentsArray[indexPath.item]
if let imageURL = imageFile.path,
imageFile.pathExtension == "jpeg",
let image = UIImage(contentsOfFile: imageURL) {
cell.imageView.image = image
} else {
fatalError("Can't create image from file \(imageFile)")
}
return cell
}
return UICollectionViewCell()
}
Populate UICollectionView Images From Document Directory AND Update Custom NSMutableArray object?
Yes! I got it figured out and it works like a charm. It seems that I could not actually update my custom NSMutableArray. I could make it read another array but could not actually change the array itself. (I'm referring to the _book.imageArray.)
Everything stayed the same in the didFinishPickingMediaWithInfo.
I didn't need to add anything to the cellForItemAtIndexPath. It is just simply:
if(_book.bookAddedToArray)
{
cell.bookImageView.image = [_book.imageArray objectAtIndex: indexPath.row];
}
I created a property for my new array:
@property (nonatomic, strong) NSMutableArray *imagePathArray;
All the magic happens in ViewDidLoad.
- (void)viewDidLoad
{
[super viewDidLoad];
//initialize new array here
_imagePathArray = [[NSMutableArray alloc] init];
if (_book.bookAddedToArray)
{
int i = 0;
//this is the path to the folder.
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:_book.imageArrayID];
int z;
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:stringPath error:NULL];
for (z = 0; z < (int)[directoryContent count]; z++)
{
//this is the path to each image file
NSString *fileName = [stringPath stringByAppendingFormat:@"/image%i.jpg", i++];
NSLog(@"imagefile = %@", fileName);
UIImage *fileNameImage = [UIImage imageWithContentsOfFile:fileName];
//add each image to a new array
[_imagePathArray addObject:fileNameImage];
}
//set my array to the new array
_book.imageArray = _imagePathArray;
}
}
I can thank this post for helping to read the images within each folder:
go to link.
//these are all properties in my Data Class.
_book.imageArrayID
_book.bookAddedToArray
_book.imageArray
I hope this helps someone out!
index out of range double array collection view
You would need to implement this differently you need multiple sections as your data consists of an array of arrays:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
cellTypes[section].count
}
and add this function:
func numberOfSections(in collectionView: UICollectionView) -> Int {
cellTypes.count
}
Way to limit collection view number of cells loaded at a time
I have placed Collection View in ScrollView Thats why it is calling All 100 cells at a time. then i removed Scroll view then it is working Fine
Related Topics
Will a a Weak Wrapper Class Throw Off a Hashable Based Collection When The Wrapped Value Is Set Nil
Uicollectionview + Nsfetchedresultscontroller in Swift 3
Using UIscrollview Correctly in Swiftui
Navigationview Inside a Tabview Swift UI
Unexpectedly Found Nil While Unwrapping an Optional Value with Avaudioplayer
Multi-Users Chat Room Data Structure in Firebase Database
How to Make an Ellipse/Circular UIimage with Transparent Background
How to Use Protocols for Stucts to Emulate Classes Inheritance
How to Create a UIprintpaper to Test UIprintinteractioncontrollerdelegate
Wkwebview on Macos Cuts Off Top
Swift Custom Response Serializer Is Returning Images at Random
How to Remove Items from an Array When Deselecting a Row in a UItableview
Swiftui List .Ondelete: Index Out of Range
Need Clarification on Anyobject in Swift
Swift 3/iOS 10/Todayextension - Userdefaults Always Returns Nil