How to display video from ALAsset to UICollectionview Cell - objective-c

I tried this code to add all ALAsset created video into my app and then play it. But the video doesn't show in UICollectionView. How is it possible?
I write this code in View Did Load.
_collectionView.dataSource=self;
_collectionView.delegate=self;
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
_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:_dic];
[_allVideos addObject:asset];
[_collectionView reloadData];
}
}];
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
And One method is
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
// result
UIImage *image = nil;
// AVAssetImageGenerator
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:#"name"];
NSLog(#"Values of dictionary==>%#", _dic);
NSLog(#"Videos Are:%#",videoURL);
CGImageRelease(halfWayImage);
}
return image;
}
And I wrote this in UICollectionView:
- (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];
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
imageview.image = [UIImage imageWithCGImage:alasset.thumbnail];
[cell.contentView addSubview:imageview];
return cell;
}

Write the code in ViewDidLoad
assets = [[NSMutableArray alloc] init];
_library = [[ALAssetsLibrary alloc] init];
UIImage *viewImage;
[_library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
}
}];
[_library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop){
if (group != NULL) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop){
if ([[result valueForProperty:ALAssetsGroupPropertyName] isEqual:#"VideoMaker"]) {
NSLog(#"asset: %#", result);
[assets addObject:result];
}
}];
}
[self.collectionView reloadData];
//[self.activity stopAnimating];
//[self.activity setHidden:YES];
}
failureBlock:^(NSError *error){
NSLog(#"failure"); }];`} `
In this assets is NSMutableArray and library is the ALAssetLibrary.
In UIcollectionviewcell cell for rowAtIndexpath method
-(VideoCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"CELL" forIndexPath:indexPath];
ALAsset *asset = [assets objectAtIndex:indexPath.row];
[cell.videoImageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
return cell;
}

Related

ALAssetsLibrary accessing all photos 1000 + from camera roll app crashes

I want to access all photos from camera roll my code is working fine if i have few images in camera roll then app is working fine but if i have more than 1000 photos then app crashes here is my code
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
NSMutableArray *arrImages=[[NSMutableArray alloc]init];
NSString *albumName = [group valueForProperty:ALAssetsGroupPropertyName];
if (albumName !=nil) {
[arrGroupsNames addObject:albumName];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
UIImage *img=[self imageForAsset:asset];
[arrImages addObject:img];
}
}
];
[arrGroups addObject:arrImages];
}
[self.tableVieww reloadData];
}
failureBlock:^(NSError *error)
{
// User did not allow access to library
NSLog(#"error");
}
];
and here is the function which return image from ALAsset
-(UIImage*) imageForAsset:(ALAsset*) aAsset{
ALAssetRepresentation *rep;
rep = [aAsset defaultRepresentation];
return [UIImage imageWithCGImage:[rep fullResolutionImage]];
}
The issue is that be creating a UIImage for each photo in the users camera roll you're going to run out of memory. This can easily be 1000+ images, and using fullResolutionImage will get the largest version of the image.
To resolve this, instead of composing an array of UIImage's, put the ALAsset in the array. Then create the UIImage from the ALAsset only when it's required on screen.
You are storing all 1000+ UIImage in an array and you are out of memory. I have the same issue, mine was 2000+ images and using the implementation below works for me.
I also suggest, you use [asset thumbnail] when displaying images especially if it's just for UITableViewCell or for other purposes that do not require the full resolution of the image.
Here a solution:
//First you need to declare `ALAssetsLibrary *al` as a global variable in the class
//
//like this:
//
//.h
#interface YOURCLASS : UIViewController
{
ALAssetsLibrary *al;
}
#end
//
//or inside your .m
//
#interface YOURCLASS ()
{
ALAssetsLibrary *al;
}
---
// you need to do this to check if 'al' is already declared and to declare once
if (al == nil)
al = [[ALAssetsLibrary alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
...
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
/*//your code
UIImage *img=[self imageForAsset:asset];
[arrImages addObject:img];
*/
//instead of storing the actual UIImage object just store the `asset` in your array
//like
[arrImages addObject:asset];
}
}];
...
}
failureBlock:^(NSError *error)
{
// User did not allow access to library
NSLog(#"error");
}];
In your table delegate cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
//you need to get the image using the stored asset
//like:
//cast what's inside the array
ALAsset *asset = (ALAsset *)self.arrGroups[indexPath.row];
//self.arrGroups[indexPath.row];
//if just for example i dont know how you access your datas
cell.imageView.image = [UIImage imageWithCGImage:[asset thumbnail]];
//getting the full resolution of the image
//[UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]]
//
//or you can simply use what you already have `[self imageForAsset:asset]`
//cell.imageView.image = [self imageForAsset:asset];
...
}
Hope is is helpful for you, Cheers!
-(void)loadCameraPhotos{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
NSMutableArray *arrImages=[[NSMutableArray alloc]init];
NSString *albumName = [group valueForProperty:ALAssetsGroupPropertyName];
if (albumName !=nil) {
[arrGroupsNames addObject:albumName];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
// if (arrImages.count<7) {
//UIImage *img=[self imageForAsset:asset];
[arrImages addObject:asset];
//}else
// *stop=YES;
}
}
];
[arrGroups addObject:arrImages];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.tableVieww reloadData];
}
failureBlock:^(NSError *error)
{
// User did not allow access to library
NSLog(#"error");
}
];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"PhotoSelectionTableViewCell";
PhotoSelectionTableViewCell* cell = (PhotoSelectionTableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"PhotoSelectionTableViewCell" owner:nil options:nil];
for(id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class] ]){
cell = (PhotoSelectionTableViewCell *)currentObject;
break;
}
}
}
NSArray *arrtemp=[arrGroups objectAtIndex:indexPath.section];
cell.lblTitle.text=[arrGroupsNames objectAtIndex:indexPath.section];
cell.lblCount.text=[NSString stringWithFormat:#"%lu",(unsigned long)arrtemp.count];
ALAsset *asset = (ALAsset *)[arrtemp lastObject];
cell.imgViewThumbnail.image=[UIImage imageWithCGImage:[asset thumbnail]];;
return cell;
}
I really doubt this solution.NSCache must be used if you want too many photos loaded asap you can see the detail in this repository https://github.com/johnil/JFImagePickerController

UICollectionView Memory Leak Crash

My CollectionView is retrieving images from the Parse network, and keeps crashing. I keep getting memory warnings right before the crash. I'm guessing I need to free up space. But the problem is i'm relatively new to coding so I don't know how to do this. I don't even know where the memory needs to be freed from. Could someone please help me understand what I am doing wrong in my code?
- (void)viewDidLoad {
[super viewDidLoad];
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:#"NavBar1.png"] forBarMetrics:UIBarMetricsDefault];
// self.navigationController.hidesBarsOnSwipe = true;
[self queryParseMethodCell];
// Do any additional setup after loading the view.
}
- (void)queryParseMethodCell {
NSLog(#"start Money");
PFQuery *query3 = [PFQuery queryWithClassName:#"MainWall"];
PFQuery *query4 = [PFQuery queryWithClassName:#"MainWall"];
[query3 orderByDescending:#"createdAt"];
[query4 orderByAscending:#"createdAt"];
[query3 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"check bobby");
imageFilesArray2 = [[NSArray alloc] initWithArray:objects];
[self.HomePost reloadData];
}
else{
NSLog(#"NO Good33");
}
}];
[query4 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"check bobby");
imageFilesArray3 = [[NSArray alloc] initWithArray:objects];
[self.HomePost reloadData];
}
else{
NSLog(#"NO Good44");
}
}];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (self.lastContentOffset > scrollView.contentOffset.y) {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
else if (self.lastContentOffset < scrollView.contentOffset.y){
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
else {
NSLog(#"Andy Error1");
}
}
- (IBAction)SwipeLeft:(UISwipeGestureRecognizer *)sender {
[self performSegueWithIdentifier:#"Notifications" sender:self];
}
- (IBAction)SwipeRight:(UISwipeGestureRecognizer *)sender{
[self performSegueWithIdentifier:#"FavWall" sender:self];
}
- (IBAction)MainWall:(id)sender{
[self performSegueWithIdentifier:#"MainWall" sender:self];
}
- (IBAction)FavWall:(id)sender{
[self performSegueWithIdentifier:#"FavWall" sender:self];
}
- (IBAction)Notifications:(id)sender{
[self performSegueWithIdentifier:#"Notifications" sender:self];
}
- (IBAction)Home:(id)sender{
[self performSegueWithIdentifier:#"Home" sender:self];
}
- (IBAction)YourAccount:(id)sender{
[self performSegueWithIdentifier:#"YourAccount" sender:self];
}
- (IBAction)UsersAccount:(id)sender{
[self performSegueWithIdentifier:#"UsersAccount" sender:self];
}
-(IBAction)PicTake:(id)sender{
[self performSegueWithIdentifier:#"Camera" sender:self];
}
#pragma mark Collection View
-(NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [imageFilesArray2 count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"TopCell";
DiscoverCell *cell = nil;
if (cell == nil) {
cell = (DiscoverCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
}
else {
NSLog(#"2Error");
}
PFObject *imageObject2 = [imageFilesArray2 objectAtIndex:indexPath.row];
cell.Username.text = [imageObject2 objectForKey:#"Name"];
PFFile *imageFile3 = [imageObject2 objectForKey:#"ProfilePicture"];
[imageFile3 getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
NSLog(#"CheckCash");
// cell.TopStory.image = [UIImage imageWithData:data];
cell.HomeImg.image = [UIImage imageWithData:data];
cell.Back.image = [UIImage imageWithData:data];
//cell.HomeImg2.image = [UIImage imageWithData:data];
}
else{
NSLog(#"NO Good");
}
cell.HomeImg.layer.cornerRadius = cell.HomeImg.frame.size.width /2;
cell.HomeImg.clipsToBounds = YES;
cell.Back.image = cell.HomeImg.image;
}];
PFObject *imageObject5 = [imageFilesArray3 objectAtIndex:indexPath.row];
cell.Username.text = [imageObject5 objectForKey:#"Name"];
PFFile *imageFile4 = [imageObject5 objectForKey:#"ProfilePicture"];
[imageFile4 getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
NSLog(#"CheckCash");
cell.TopStory.image = [UIImage imageWithData:data];
}
else{
NSLog(#"NO Good22");
}
}];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You have a memory leak. Everytime you scroll all images all reloaded. Something like this should solve the problem
//at start For every data DataisNotLoaded should be true
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if dataisNotLoaded[index] {
DataisNotLoaded[index] = false
[imageFile3 getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
NSLog(#"CheckCash");
// cell.TopStory.image = [UIImage imageWithData:data];
cell.HomeImg.image = [UIImage imageWithData:data];
cell.Back.image = [UIImage imageWithData:data];
//cell.HomeImg2.image = [UIImage imageWithData:data];
}
else{
NSLog(#"NO Good");
}
}

iCarousel + Parse: Loading Async Images from PFObject

I am trying to populate an iCarousel with a parse (parse.com, pfoject) object without success.
I can't find any example of how to do it, so it why i am asking here...
- (void)viewDidLoad
{
[super viewDidLoad];
_items = [NSMutableArray array];
PFQuery *query = [PFQuery queryWithClassName:#"testUser"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded. The first 100 objects are available in objects
[_items addObjectsFromArray:objects];
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
//configure carousel
_carousel.type = iCarouselTypeRotary;
//_carousel.viewpointOffset = CGSizeMake(0.0f, 100.0f);
[_carousel setContentOffset:CGSizeMake(0.0f, -60.0f)];
}
And at viewForItemAtIndex:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
//create new view if no view is available for recycling
if (view == nil)
{
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300.0f, 300.0f)];
}
PFObject *eachObject = [_items objectAtIndex:index];
PFFile *theImage = [eachObject objectForKey:#"image"];
NSData *imageData = [theImage getData];
UIImage *image = [UIImage imageWithData:imageData];
((UIImageView *)view).image = image;
view.contentMode = UIViewContentModeCenter;
return view;
}
Please, any help? :-(
In viewDidLoad, After the
[_items addObjectsFromArray:objects];
Put
[_carousel reloadData];
Otherwise the carousel won't be updated after the items have been added to the array, so you'll still be looking at an empty carousel.

Issue in Using AsyncImageView in icarousel in iOS

I have developed an app which uses Asyncimageview and iCarousel.But my issues is that when i'm trying to load the images from urls only activity indicator loads in each view of my iCarousel and no images are loaded.Here is my code
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
if (view == nil
 {
AsyncImageView * view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
}
return view;
}
Follow these steps maybe because of following reasons you may face this issue
-- Check whether if ur imageURLs array is having objects under iCarousel are not...If its null you may have this kind of issue....
-- Do array allocation and add objects in
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
method,because if you add objects in your array under viewDidLoad it won't works because carousel view loads first before viewDidLoad method..
-- if your array element is present even after these steps follow this code.
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
//NSLog(#"%#",imageURLs)//check imageURLs having object
if(view ==nil)
{
[[AsyncImageLoader sharedLoader]cancelLoadingImagesForTarget:view];
}
return view;
}
It will help you..
Cells should be reused
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(AsyncImageView *)view
{
if (view == nil) {
view = [[[AsyncImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 280)] autorelease];
}
// dont forget stop previous loading -cancelLoadingURL:target:
view.image=[UIImage imageNamed:#"infobg.png"];
view.imageURL=[imageURLs objectAtIndex:index];
return view;
}
also you should stop previously started
- (void)viewDidLoad
{
[super viewDidLoad];
User_Id=#"abcd#gmail.com";
NSString *Post=[NSString stringWithFormat:#"email=%#",User_Id];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:#"%d",[Post length]];
NSURL *Url=[NSURL URLWithString:[NSString stringWithFormat:#"%#fetch_all_user_updates.php",ServerPath]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:PostLengh forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
Response = [Response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray *JSON_Array=[Response JSONValue];
// NSlog(#"%#", JSON_Array);
// textfield.text=[[JSON_Array valueforKey:#"email"]objectAtIndex:0];
// load images from database at local host
/*
NSLog(#"%#",[NSString stringWithFormat:#"%#/Images/%#",serverScriptpath,[[jsonarray valueForKey:#"image"]objectAtIndex:0]]);
NSURL *img_url=[NSURL URLWithString:[NSString stringWithFormat:#"%#/Images/%#",
serverScriptpath,[[jsonarray valueForKey:#"image"]objectAtIndex:0]]];
NSURLRequest *request1=[NSURLRequest requestWithURL:img_url];
[Img_profilepic setImageWithURLRequest:request1 placeholderImage:[UIImage imageNamed:#".png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
}];
*/
if (JSON_Array>0)
{
Array_Image_Name=[JSON_Array valueForKey:#"image_name"];
[Array_Image_Name retain];
}
else
{
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:#"Failure" message:#"Error To Load Image" delegate:Nil cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[Alert show];
[Alert release];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return Array_Image_Name.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell=nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
AsyncImageView *Load_Image=[[AsyncImageView alloc]initWithFrame:CGRectMake(20, 10, 280, 100)];
Load_Image.imageURL=[NSURL URLWithString:[NSString stringWithFormat:#"%#/Images/%#",ServerPath,[Array_Image_Name objectAtIndex:indexPath.row]]];
Load_Image.showActivityIndicator=YES;
[cell.contentView addSubview:Load_Image];
return cell;
}
AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(0.0f, 1.0f, 320.0f, 174.0f)];
NSString *imgUrlString = photobig1;
while ([imgUrlString rangeOfString:#" "].location != NSNotFound) {
imgUrlString = [imgUrlString stringByReplacingOccurrencesOfString:#" " withString:#""];
}
UIImageView *imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Loading Image.png"]];
[asyncImage addSubview:imageview];
asyncImage.tag = 999;
NSString *webStr = [NSString stringWithFormat:#"%#",imgUrlString];
NSURL *imageUrl = [[NSURL alloc] initWithString:[webStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[asyncImage loadImageFromURL:imageUrl];
[asyncImage setBackgroundColor:[UIColor clearColor]];
asyncImage.userInteractionEnabled = NO;
[scrollView addSubview:asyncImage];

CoreData - could not locate an NSManagedObjectModel

I'm getting the error below, I don't know what I'm doing wrong.
I guess there is the managedobject which cannot be located, but... arf !
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Boxes''
here is my .m ( only the two main functions )
- (void)loadCoreData
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test" object:self];
context = [app managedObjectContext];
NSError *err;
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
}
- (void) fillSexArray:(NSString *)sexe
{
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
NSPredicate *sex;
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
// NSUInteger numObjects = [mutableArray count];
}
my .h :
#interface AddViewController : UIViewController
{
IBOutlet UIButton *male;
IBOutlet UIButton *female;
IBOutlet UIButton *couple;
UIButton *maleBtn;
BOOL flag;
NSArray *arrayForPredicate;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *context;
NSFetchRequest *request;
}
#property (nonatomic, retain) WonderAppDelegate *app;
- (void) fillSexArray:(NSString *)sexe;
- (NSMutableArray *)createMutableArray:(NSArray *)array;
- (void)loadCoreData;
- (void)sexeButtonPressed;
- (void)sexeArray;
#end
EDIT creating the managedObject :
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes"
inManagedObjectContext:managedObjectContext];
boxes.name = [dict objectForKey:#"name"];
boxes.sexe = [dict objectForKey:#"sexe"];
boxes.topic = [dict objectForKey:#"topic"];
boxes.number = [dict objectForKey:#"number"];
return boxes;
}
This is my .m and it is working like that but i don't want the code of the function Add there i want it on loadCoreData.
//
// AddViewController.m
// CoreDataTuto
//
// Created by Clement Yerochewski on 30/04/12.
// Copyright (c) 2012 Weblib. All rights reserved.
//
#import "AddViewController.h"
#import "Boxes.h"
#implementation AddViewController
#synthesize app, context;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:#"Add Detail"];
[navBar pushNavigationItem:navItem animated:NO];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(cancel)];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Add" style:UIBarButtonItemStyleBordered target:self action:#selector(add)];
navItem.leftBarButtonItem = cancelButton;
navItem.rightBarButtonItem = addButton;
[self.view addSubview:navBar];
app = [[UIApplication sharedApplication] delegate];
}
return self;
}
- (void) add{
[self dismissModalViewControllerAnimated:YES];
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH A LENGTH NAME <= 5
// NSPredicate *length;
// length = [NSPredicate predicateWithFormat:#"name.length <= 5"];
// NSArray *BoxWithCheapPrice = [array filteredArrayUsingPredicate:length];
// NSLog(#"Box %#", BoxWithCheapPrice);
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH PRICE BETWEEN $MIN AND $MAX
// NSNumber *min = [NSNumber numberWithInteger:30];
// NSNumber *max = [NSNumber numberWithInteger:100];
// NSPredicate *between;
// between = [NSPredicate predicateWithFormat:#"number BETWEEN %#", [NSArray arrayWithObjects:min, max, nil]];
// NSArray *BoxWithPriceBetween = [array filteredArrayUsingPredicate:between];
// NSLog(#"Box %#", BoxWithPriceBetween);
// NSLog(#"%#", [BoxWithPriceBetween valueForKey:#"name"]);
}
- (NSMutableArray *)createMutableArray:(NSArray *)array
{
return [NSMutableArray arrayWithArray:array];
}
- (IBAction) sexeChoosen: (id) sender
{
switch ( ((UIButton*)sender).tag ){
case 0:
[self fillSexArray:#"male"];
break;
case 1:
[self fillSexArray:#"female"];
break;
default:
[self fillSexArray:#"both"];
}
[self sexeButtonPressed];
}
- (void)sexeButtonPressed
{
if (flag)
{
UIImage * maleImg2 = [UIImage imageNamed:#"pressed.png"];
[maleBtn setImage:maleImg2 forState:UIControlStateNormal];
flag = NO;
[self sexeArray];
}
else
{
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
flag = YES;
[self sexeArray];
}
}
- (void)sexeArray
{
}
- (void)loadCoreData
{
}
- (void) fillSexArray:(NSString *)sexe
{
context = [app managedObjectContext];
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError *err;
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
NSPredicate *sex;
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
NSLog(#"SEXE CHOOSEN %#", mutableArray);
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
NSUInteger numObjects = [mutableArray count];
NSLog(#"%d", numObjects);
}
- (void) cancel{
[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
flag = YES;
maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maleBtn.frame = CGRectMake(40, 47, 107, 75);
[maleBtn setTitle:#"male" forState:UIControlStateNormal];
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
[maleBtn addTarget:self action:#selector(sexeChoosen:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:maleBtn];
[self loadCoreData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Have you updated your model after creating the persistent store? Try to delete your app from the simulator (or the database file) and run it again..