This only returns some of the albums from Photos and the albums I'm getting doesn't include the same number of assets as there are images in them in the Photos app.
NSMutableArray *groups = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[groups addObject:group];
} else {
block([groups copy], nil);
}
}
failureBlock:^(NSError *error) {
block(nil, error);
}];
What do I need to do to get all 1000 of them?
something like
- (void)loadLibraryGroups
{
if (self.assetsLibrary == nil) {
_assetsLibrary = [[ALAssetsLibrary alloc] init];
}
if (self.groups == nil) {
_groups = [[NSMutableArray alloc] init];
} else {
[self.groups removeAllObjects];
}
// setup our failure view controller in case enumerateGroupsWithTypes fails
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
NSString *errorMessage = nil;
switch ([error code]) {
case ALAssetsLibraryAccessUserDeniedError:
case ALAssetsLibraryAccessGloballyDeniedError:
errorMessage = #"The user has declined access to it.";
break;
default:
errorMessage = #"Reason unknown.";
break;
}
};
// emumerate through our groups and only add groups that contain photos
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
[group setAssetsFilter:onlyPhotosFilter];
if ([group numberOfAssets] > 0)
{
NSLog(#"group ==> %#",group);
[self.groups addObject:group];
}
else
{
NSLog(#"Empty Groups load all items");
for (ALAssetsGroup *group in self.groups) {
[self loadImageForEachGroup:group];
}
}
};
// enumerate only photos
NSUInteger groupTypes = ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos;
[self.assetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:listGroupBlock failureBlock:failureBlock];
NSLog(#"finish load groups");
}
- (void)loadImageForEachGroup:(ALAssetsGroup *)group
{
if (!self.assets) {
_assets = [[NSMutableArray alloc] init];
} else {
[self.assets removeAllObjects];
}
ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result != nil) {
[self.assets addObject:result];
} else {
[self.collectionView reloadData];
}
};
ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
[group setAssetsFilter:onlyPhotosFilter];
[group enumerateAssetsUsingBlock:assetsEnumerationBlock];
}
And Load in collection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.assets.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"photoCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell
// load the asset for this cell
ALAsset *asset = self.assets[indexPath.row];
CGImageRef thumbnailImageRef = [asset thumbnail];
UIImage *thumbnail = [UIImage imageWithCGImage:thumbnailImageRef];
// apply the image to the cell
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
imageView.image = thumbnail;
return cell;
}
Related
I am trying to fetch the video list from gallery to collection view by using ALAssetLibrary.But the video doesn't display in collection view.
And getting the Error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier cellIdentifier - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
*** First throw call stack:
(0x2ba0749f 0x395fbc8b 0x2ba07375 0x2c6d8d7f 0x2f4cb573 0x2ef26cd1 0x580d7 0x2ef268f5 0x2ef24fc1 0x2ef20c09 0x2eec724f 0x2e8efa0d 0x2e8eb3e5 0x2e8eb26d 0x2e8eac51 0x2e8eaa55 0x2e8e492d 0x2b9cdd95 0x2b9cb453 0x2b9cb85b 0x2b9193c1 0x2b9191d3 0x32cfd0a9 0x2ef28fa1 0x6de09 0x39b7baaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
Please help me to solve this.
my code is here--
Create a collection view by using this code in viewDidLoad():
self.view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
[collectionView setDataSource:self];
[collectionView setDelegate:self];
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[collectionView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:collectionView];
Load Asset like this--
loadAssets()
{
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:asset];
}
}];
[_collectionView reloadData];
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
UIImage *image = nil;
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// cgimage to uiimage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"ImageThumbnail"];//kImage
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",allVideos);
CGImageRelease(halfWayImage);
}
return image;
}
-(void)viewDidAppear:(BOOL)animated
{
[self loadAssets];
}
And in collection View--
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [allVideos count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSLog(#"allvideo %#", allVideos);
ALAsset *alasset = [allVideos objectAtIndex:indexPath.row];
return cell;
}
I am trying to display images from Photo Library in UICollectionView through ALAssetsLibrary my codes runs fine , but I have some issues .
The quality of thumbnails are poor .
How can arrange collection view show 100 recent photos by ordering
from
new to old .
here is my codes :
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// collect the photos
NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
ALAssetsLibrary *al = [ViewController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset) {
[collector addObject:asset];
}
}];
self.photos = collector;
}
failureBlock:^(NSError *error) { NSLog(#"error");}];
}
-(void)setPhotos:(NSArray *)photos {
if (_photos != photos) {
_photos = photos;
[_collectionView reloadData];
}
}
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred, ^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _photos.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *collectionImageView = (UIImageView *)[cell viewWithTag:100];
ALAsset *asset = [self.photos objectAtIndex:indexPath.row];
UIImage* img = [UIImage imageWithCGImage:asset.thumbnail];
img = [UIImage imageWithCGImage:img.CGImage scale:2.0 orientation:UIImageOrientationUp];
[collectionImageView setImage:img];
return cell;
}
Use the following code to sort the photos.
self.photos = [collector sortedArrayUsingComparator:^NSComparisonResult(ALAsset *first, ALAsset *second) {
NSDate * date1 = [first valueForProperty:ALAssetPropertyDate];
NSDate * date2 = [second valueForProperty:ALAssetPropertyDate];
return [date1 compare:date2];
}];
You can get the date of an image saved in the library by:
NSDate * date = [asset valueForProperty:ALAssetPropertyDate];
You can compare this date with today's date, and store it an array, and do the same for the 100 Images.
And to your other question,
The thumbnail img you get from asset is of different size depends on iOS. In iOS 9 it is of 75x75 and in iOS 8, it is of 150x150.
You can try this:
[UIImage imageWithCGImage:[asset aspectRatioThumbnail]
I am fetching contact from device and show in tableview
but first time on contact screen pop show for contact permission, when i click on okey tableview numberofrow called but cellForRowAtIndexPath calling after 5 seconds
I am using this code (this problem only comes first time when new app install)
and i added delegate and datasource in xib and .h file
-(void)getContactsFromAddressBook
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted)
[self loadContacts];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
[self loadContacts];
}
else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:Nil message:#"You don't have permission of access contacts for access go to Setting-> Doubls-> Contacts" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
//Load contact
-(void)loadContacts
{
[arr_Contact removeAllObjects];
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
//arr_Contact = (__bridge NSMutableArray*)allPeople;
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
//NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString *phoneNumber;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
// NSLog(#"phone:%#", phoneNumber);
}
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
if(firstName == nil)
{
firstName = #"";
}
if(lastName == nil)
{
lastName = #"";
}
if(phoneNumber == nil)
{
continue;
}
[dic setValue:[NSString stringWithFormat:#"%# %#",firstName,lastName] forKey:#"firstName"];
//[dic setValue:lastName forKey:#"lastName"];
[dic setValue:phoneNumber forKey:#"phonesNum"];
[arr_Contact addObject:dic];
}
NSLog(#"arr all contact %#",arr_Contact);
NSSortDescriptor *sorter = [[NSSortDescriptor alloc]
initWithKey:#"firstName"
ascending:YES
selector:#selector(compare:)] ;
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[arr_Contact sortUsingDescriptors:sortDescriptors];
[arr_afterSearch addObjectsFromArray:arr_Contact];
[self createSectionList:arr_Contact];
}
//create section
- (void) createSectionList: (id) wordArray
{
for (int i = 0; i < 27; i++) [arr_searchContact addObject:[[NSMutableArray alloc] init]];
int k=0;
NSLog(#"arr count is %lu",(unsigned long)[arr_Contact count]);
for (k=0; k<[arr_Contact count]; k++) {
NSString *word = [NSString stringWithFormat:#"%#",[[arr_Contact valueForKey:#"firstName"]objectAtIndex:k]];
if ([word length] == 0) continue;
#try {
range1 = [ALPHA rangeOfString:[[word substringToIndex:1] uppercaseString]];
[[arr_searchContact objectAtIndex:range1.location]addObject:[arr_Contact objectAtIndex:k]];
}
#catch (NSException * e) {
[[arr_searchContact objectAtIndex:26]addObject:[arr_Contact objectAtIndex:k]];
NSLog(#"error");
}
#finally {
}
}
[self.tblContact reloadData];
}
//tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows=0;
if (IsSearching==TRUE) {
rows=[arr_afterSearch count];
}
else{
rows=[[arr_searchContact objectAtIndex:section] count];
}
return rows;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger section=0;
if (IsSearching==TRUE) {
section=1;
}
else{
if ([arr_searchContact count]>0) {
section=[ALPHA_ARRAY count];
}
else{
section=0;
}
}
return section;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
if (IsSearching==TRUE) {
return nil;
}
else{
return ALPHA_ARRAY;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
// create the parent view that will hold header Label
if (IsSearching==TRUE) {
return nil;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return nil;
}
else {
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(5.0, 0.0, 320.0, 25.0)];
[customView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:239.0/255.0 blue:240.0/255.0 alpha:1.0]];
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.font = [UIFont systemFontOfSize:14];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 24.0);
[headerLabel setText:[NSString stringWithFormat:#"%#",[ALPHA_ARRAY objectAtIndex:section]]];
[headerLabel setTextColor:[UIColor lightGrayColor]];
[customView addSubview:headerLabel];
return customView;
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (IsSearching==TRUE) {
return 0;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return 0;
}
else
{
return 25;
}
}
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
UIView *selectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 46)];
[selectionView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:82.0/255.0 blue:91.0/255.0 alpha:1.0]];
cell.selectedBackgroundView = selectionView;
if ([tableView respondsToSelector:#selector(setSectionIndexColor:)]) {
tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:0.3];
tableView.sectionIndexTrackingBackgroundColor = [UIColor whiteColor];
}
}
NSMutableDictionary *dic = [arr_Contact objectAtIndex:indexPath.row];
//cell.textLabel.text = [dic objectForKey:#"firstName"];
//cell.lastNameLabel.text = [dic objectForKey:#"lastName"];
if (IsSearching==TRUE) {
NSDictionary *dic=[arr_afterSearch objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
else{
NSDictionary *dic=[[arr_searchContact objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
cell.textLabel.textColor=[UIColor darkGrayColor];
cell.textLabel.highlightedTextColor = [UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:#"OpenSans" size:14.0];
return cell;
}
You need to ensure that you only update the UI from the main queue. Your completion handler for the address book access will be executing on a background thread. Change the completion handler to invoke loadContacts on the main queue.
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[self loadContacts];
});
}
});
I'm using a storyboard and my custom UICollectionViewCell is not appearing. I played around with it for a few hours and have googled a ton of different solutions but none worked. Just to clarify, the data exists, and the UICollectionView is appearing, but the cell is not. Here is my code. Any suggestions would be appreciated!
- (NSInteger)collectionView:(UICollectionView *)mutualFriendsView numberOfItemsInSection:(NSInteger)section {
return [self.resultsDictionary count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)mutualFriendsView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"PCRRequesterMutualFriendsCollectionViewCell";
PCRRequesterMutualFriendsCollectionViewCell *cell = [self.mutualFriendsView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSArray *idArray = [self.resultsDictionary objectForKey:#"id"];
NSArray *nameArray = [self.resultsDictionary objectForKey:#"name"];
cell.profileName.text = [nameArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor redColor];
return cell;
}
- (void)collectionView:(UICollectionView *)mutualFriendsView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell #%d was selected", indexPath.row);
}
- (BOOL)shouldAutorotate {
[mutualFriendsView.collectionViewLayout invalidateLayout];
BOOL retVal = YES;
return retVal;
}
EDIT Here is my viewDidLoad
self.mutualFriendsView.dataSource = self;
self.mutualFriendsView.delegate = self;
self.mutualFriendsView.pagingEnabled = YES;
// [self.mutualFriendsView registerClass:[PCRMutualFriendsCollectionViewCell class] forCellWithReuseIdentifier:#"PCRMutualFriendsCollectionViewCell"];
Edit I think I figured out the problem. I don't think the dictionary is being populated after the completion block finishes. Any suggestions for saving the value of the dictionary from the block to be used outside of it?
__block NSMutableDictionary *mutualFriends = nil;
__block NSNumber *total;
NSString *u = [NSString stringWithFormat:#"%#",self.details[#"Requester"][#"profile"][#"facebookId"]];
/* make the API call */
[FBRequestConnection startWithGraphPath:(#"/%#", u)
parameters:params
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
/* handle the result */
if (!error){
NSLog(#"RESULT OF FB %#", result);
if (result == nil){
NSLog(#"No shared friends");
} else {
total = result[#"context"][#"mutual_friends"][#"summary"][#"total_count"];
NSLog(#"TOTAL FRIENDS %#", total);
for(int i=0;i<[result[#"context"][#"mutual_friends"][#"data"] count];i++)
{
mutualFriends = result[#"context"][#"mutual_friends"][#"data"][i];
NSLog(#"FRIENDDATA %#", mutualFriends);
}
}
} else {
NSLog(#"ERROR %#", error);
}
}];
self.resultsDictionary = mutualFriends;
self.number = total;
NSLog(#"NUMBER %#", self.number);
NSLog(#"RESULTS DICTIONARY %#", self.resultsDictionary);
NSString *friends = [NSString stringWithFormat:#"You have %# friends in common including:", self.number];
After this code:
for(int i=0;i<[result[#"context"][#"mutual_friends"][#"data"] count];i++)
{
mutualFriends = result[#"context"][#"mutual_friends"][#"data"][i];
NSLog(#"FRIENDDATA %#", mutualFriends);
}
// add
self.resultsDictionary = mutualFriends;
mutualFriendsView.reloadData();
All within that completion block. So when FB finally does return and you've accumulated all the mutualFriends, then you tell the collectionView to reload.
Hi i have implemented UICollectionView in my app..If my array count value greater than 20 and when i tried to scroll the view it was not showing previous datas,,
In cellForItemAtIndexPath:(NSIndexPath *)indexPath method every time i check
if (indexPath.row == [recipeImages count] - 1)
{
[self loadDatas];
}
method.So that i could download 10 datas everytime...
-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionViewcellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"CourseList";
NSLog(#"indexpath %# in cell for row",indexPath);
CollectionCellContent *cell = (CollectionCellContent*)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSDictionary *course;
course=[courselist objectAtIndex:indexPath.row];
cell.coursename.text=[course objectForKey:#"course_name"];
cell.authorname.text=[course objectForKey:#"course_author"];
cell.price.text=[course objectForKey:#"course_price"];
cell.cover.image=[UIImage imageNamed:[course objectForKey:#"course_cover_image"]];
cell.review.image=[UIImage imageNamed:[course objectForKey:#"ratings"]];
NSString *imageUrlString = [[NSString alloc]initWithFormat:#"%#/%#/%#",delegate.course_image_url,[course objectForKey:#"course_id"],[course objectForKey:#"course_cover_image"]];
UIImage *imageFromCache = [self.imageCache objectForKey:imageUrlString];
if (imageFromCache) {
cell.cover.image= imageFromCache;
}
else
{
cell.cover.image = [UIImage imageNamed:#"placeholder"];
[self.imageOperationQueue addOperationWithBlock:^{
NSURL *imageurl = [NSURL URLWithString:imageUrlString];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageurl]];
if (img != nil) {
[self.imageCache setObject:img forKey:imageUrlString];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
CollectionCellContent *updateCell = (CollectionCellContent*)[self.ipadcollection cellForItemAtIndexPath:indexPath];
if (updateCell) {
[updateCell.cover setImage:img];
}
}];
}
}];
}
if (indexPath.row == [courselist count] - 1)
[self loadDatas];
return cell;
}
in load datas method:
[categorylist addObject:[arrayList1 objectForKey:#"category_name"]];
[category_tableView reloadData];
whenever i call reload data method i am facing this issue..
-(void)loadDatas
{
NSString *urltemp=[[databaseurl sharedInstance]DBurl];
NSString *url1=#"AllCourse.php";
NSString *URLString=[NSString stringWithFormat:#"%#%#?offset=%d",urltemp,url1,offset];
NSMutableArray *search = [du MultipleCharacters:URLString];
NSDictionary* menu = [search valueForKey:#"serviceresponse"];
NSArray *Listofdatas=[menu objectForKey:#"Course List"];
NSMutableArray *temp1=[[NSMutableArray alloc]init];
if ([Listofdatas count]>0)
{
for (int i=0;i<[Listofdatas count];i++)
{
NSDictionary *arrayList1= [Listofdatas objectAtIndex:i];
NSDictionary* temp=[arrayList1 objectForKey:#"serviceresponse"];
// NSLog(#"Received Values %#",temp);
if (offset==0) {
[courselist addObject:temp];
}
else
[temp1 addObject:temp];
}
if (offset!=0)
{
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (NSInteger index =courselist.count; index < (courselist.count + temp1.count); index++) {
[arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
}
if (courselist) {
[courselist addObjectsFromArray:temp1];
[self.ipadcollection performBatchUpdates:^{
[self.ipadcollection insertItemsAtIndexPaths:arrayWithIndexPaths];
}
completion:nil];
// [self.collectionView reloadData];
}
else {
courselist = [[NSMutableArray alloc] initWithArray:temp1];
}
}
if (![HUD isHidden]) {
[HUD hide:YES];
}
}
offset+=10;
[self.ipadcollection reloadData];
}
Make some delay before reloading UICollectionView.
[self performSelector:#selector(reloaddatas) withObject:nil afterDelay:0.5f];