Skip to content

Instantly share code, notes, and snippets.

@morganwilde
Last active December 29, 2015 16:09
Show Gist options
  • Save morganwilde/7695597 to your computer and use it in GitHub Desktop.
Save morganwilde/7695597 to your computer and use it in GitHub Desktop.
UITableView with ALAssets
@interface ViewControllerStudentsList ()
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) UIManagedDocument *document;
@property (nonatomic) NSInteger studentCount;
@property (strong, nonatomic) NSMutableArray *studentList;
@property (strong, nonatomic) NSMutableDictionary *studentPortraits;
@end
@implementation ViewControllerStudentsList
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"studentCell";
StudentTableCell *cell = (StudentTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
// Never gets called
}
Student *student = self.studentList[indexPath.row];
cell.nameFirst.text = student.nameFirst;
cell.nameLast.text = student.portrait.assetURL;
// Portrait
UIImage *portrait = [self cachedStudentPortrait:student atIndexPath:(NSIndexPath *)indexPath];
if (!portrait) {
portrait = [UIImage imageNamed:@"portrait-placeholder-1"];
}
cell.portrait.image = portrait;
return cell;
}
- (UIImage *)cachedStudentPortrait:(Student *)student atIndexPath:(NSIndexPath *)indexPath
{
UIImage *portrait = nil;
NSString *objectClassName = NSStringFromClass([self.studentPortraits[student.studentID] class]);
if ([objectClassName isEqualToString:@"UIImage"]) {
portrait = self.studentPortraits[student.studentID];
} else {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSLog(@"student.portrait.assetURL: %@", student.portrait.assetURL);
[library assetForURL:[NSURL URLWithString:student.portrait.assetURL] resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef assetRef = [representation fullResolutionImage];
if (assetRef) {
self.studentPortraits[student.studentID] = [UIImage imageWithCGImage:assetRef];
[self.table reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
} failureBlock:^(NSError *error) {
// error handling
NSLog(@"failed to load");
}];
}
return portrait;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment