I need to show flickr public images in a UICollectionView. I have done all the things, but images don't load in the UICollectionView. I am new to objective-c. Please help.
authorIds = [[NSMutableArray alloc] init];
dateTaken = [[NSMutableArray alloc] init];
smallImageUrlArray = [[NSMutableArray alloc] init];
largeImageUrlArray = [[NSMutableArray alloc] init];
smallImageArray = [[NSMutableArray alloc] init];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
layout.sectionInset = UIEdgeInsetsMake(110, 20, 20, 20);
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:_collectionView];
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return totalImageNo;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image = [UIImage imageNamed:[smallImageUrlArray objectAtIndex:indexPath.row]];
//[self.view addSubview:cellImageView];
[cell.backgroundView addSubview:cellImageView];
// NSLog(#"%#",[smallImageUrlArray objectAtIndex:indexPath.row]); //Here can show Img's values correctly
cell.backgroundColor=[UIColor darkGrayColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(160, 160);
}
In below I am fetching Flickr images and storing in array. then want to load the smallImageArray in the UICollection view. but nothing shows up.
-(void)fetchFlickrPublicImages
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=data"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *badJSON = [NSData dataWithContentsOfURL:url];
NSString *dataAsString = [NSString stringWithUTF8String:[badJSON bytes]];
NSString *correctedJSONString = [NSString stringWithString:[dataAsString substringWithRange:NSMakeRange (15, dataAsString.length-15-1)]];
correctedJSONString = [correctedJSONString stringByReplacingOccurrencesOfString:#"\\'" withString:#"'"];
NSData *correctedData = [correctedJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:correctedData options:kNilOptions error:&error];
NSArray *images = [json objectForKey:#"items"];
for (NSDictionary *image in images)
{
NSString *authorId = [image objectForKey:#"author_id"];
[authorIds addObject:(authorId.length > 0 ? authorId: #"Untitled")];
NSString *largeImageUrl = [NSString stringWithFormat:#"%#",[[image objectForKey:#"media"] objectForKey:#"m"]];
NSString *smallImageUrl = [largeImageUrl stringByReplacingOccurrencesOfString:#"_m" withString:#"_s"];
[smallImageUrlArray addObject:smallImageUrl];
[dateTaken addObject:[NSString stringWithFormat:#"%#",[image objectForKey:#"date_taken"]]];
[largeImageUrlArray addObject:[NSString stringWithFormat:#"%#",[[image objectForKey:#"media"] objectForKey:#"m"]]];
totalImageNo = authorIds.count;
}
for (int i=0; i< smallImageUrlArray.count; i++) {
UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[smallImageUrlArray objectAtIndex:i]]]];
[smallImageArray addObject:image];
}
NSLog(#"%#", smallImageArray);
NSLog(#"%ld", (long)totalImageNo);
// NSLog(#"authorIds: %#\n\n", authorIds);
// NSLog(#"photoURLsLareImage: %#\n\n", smallImageUrlArray);
// NSLog(#"photoURLsLareImage: %#\n\n", largeImageUrlArray);
}
You should add your UIImageView to the collection view cell's contentView, NOT backgroundView.
In your code ,
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image = [UIImage imageNamed:[smallImageUrlArray objectAtIndex:indexPath.row]];
[cell.backgroundView addSubview:cellImageView];
}
you are assigning image as url . but in your method named fetchFlickrPublicImages where you are downloading images directly.
better you write code like
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image =(UIImage*)[smallImageArray objectAtIndex:indexPath.row];
[cell.contentView addSubView cellImageView];
}
Related
I need to get several URLs of photos from a server and display them in a collectionview. The thing is, they provide a api called
"findObjectsInBackgroundWithBlock" to let me download URLs from server. It automatically download from server in background.I'm trying to use dispatch_async but it seems has some trouble with collectionview. Any ideas?
BmobQuery *picturesB = [BmobQuery queryWithClassName:#"AssetPicture"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[picturesB findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error)
{
for (BmobObject *obj in array)
{
[photourl addObject:[obj objectForKey:#"imageUrl"]];
}
for (int i = 0; i < 12; i++) {
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:photourl[i]]];
[self.arr addObject:[UIImage imageWithData:imageData]];
}
}];//Bmob query
if(self.arr!=nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
self.collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:flowLayout];
[self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:#"MyCollectionCell"];
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.collectionView];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView registerClass:[CollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"Header"];
});// dispatch
}//if
});//dispatch
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"MyCollectionCell" forIndexPath:indexPath];
cell.imageView.image = [self.arr objectAtIndex:indexPath.row];
NSLog(#"photo done");
cell.descLabel.text = [[NSString alloc] initWithFormat:#"{%ld,%ld}",indexPath.section,indexPath.row];
return cell;
}
Im using the following code to load images from url into collection view
-
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
UILabel *recipeLabel = (UILabel *)[cell viewWithTag:200];
if ([ImageArray count] >0){
for(int i = 0; i < [ImageArray count]; i++)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL: [NSURL URLWithString:[ImageArray objectAtIndex:indexPath.row]]];
UIImage *image = [UIImage imageWithData: data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
recipeImageView.image = image;
});
});
}
}else{
UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
title.text = #"No image record found";
title.tag = 200;
[title setHidden:true];
[cell.contentView addSubview:title];
}
[spinnerShow stopAnimating];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
If the ImageArray has got some url, if loop will be executed. Else the else loop will be executed where it will display a label saying no image record found. But the uilabel is not getting visible
Why are you using for loop in cellForItemAtIndexPath? This method is called for every item in UICollectionView. In else condition, add log or breakpoint and check if it is going there or always going in if condition. Make sure if you need to check for array count or want to check if image exists on URL?
I'm trying to display image from documents directory in UICollectionView, everything works fine, but no image appears
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize recipe image array
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *image = [NSMutableArray array];
for (NSString *tString in dirContents) {
if ([tString hasSuffix:#".png"]) {
[image addObject:tString];
listeImages = [NSArray arrayWithArray:image];
}
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return listeImages.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
UILabel *LabelView = (UILabel *)[cell viewWithTag:110];
LabelView.text = [listeImages objectAtIndex:indexPath.row];
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
NSLog(#" List UIImageView listeImageView.image %#",listeImageView.image);
cell.backgroundColor = [UIColor redColor];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame.png"]];
NSLog(#" List NSArray *listeImages %#",listeImages);
cell.tag = indexPath.row;
return cell;
}
with this piece of code, displays the correct UICollectionView UILabel well but no image is displayed.
I use this line of code to store my image in listeImageView.image.
UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
Here are the results of my NSLog:
2014-10-11 09:46:31.117 imgapp[2803:60b] List NSArray *listeImages; (
"image10102014233607.png",
"image10102014233616.png",
"image10102014233627.png"
)
2014-10-11 09:46:31.158 imgapp[2803:60b] List UIImageView listeImageView.image (null)
2014-10-11 09:46:31.171 imgapp[2803:60b] List UIImageView listeImageView.image (null)
2014-10-11 09:46:31.178 imgapp[2803:60b] List UIImageView listeImageView.image (null)
any help will be appreciated.
Thanks
You have below,
listeImageView.image = [UIImage imageNamed:[listeImages objectAtIndex:indexPath.row]];
But your doing,
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame.png"]];
Why your not using your listeImageView as below:-
cell.backgroundView = listeImageView;
That should get you the image.
UPDATE :-
for (NSString *tString in dirContents) {
if ([tString hasSuffix:#".png"]) {
**[image addObject:[UIImage imageWithContentsOfFile:tString] ]; //Do this as in below line you were not create a image object which you are trying to get.**
//Also check your image array for object, that is it getting stored or not.
// [image addObject:tString];
}
}
listeImages = [NSArray arrayWithArray:image]; //Do this after you have added all objects in your image mutable array and not in for loop as this will initialise it many tiems depending on your loop run count.
You're not adding your listeImageView to anything.
Try it with
[cell addSubview:listeImageView];
or if you really want it to be the backgroundView
cell.backgroundView = listeImageView;
But it'd be much cleaner if you create a custom UICollectionViewCell-class where you can define what content this cell has.
Have u tried to give background color to cell instead of backgroundview.do that once if possible with same code of yours!
Or
You can try like :-UIImageView *listeImageView = (UIImageView *)[cell viewWithTag:100];
[cell bringviewtoFront:listeImageView ];
You'd be much better off subclassing UICollectionViewCell, and setting up the subviews in a storyboard. Your code could be much cleaner this way:
static NSString *kCustomCellIdentifier = #"customcell";
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MYAPPCustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCustomCellIdentifier forIndexPath:indexPath];
// Load custom image
NSString *imageName = [listeImages objectAtIndex:indexPath.row];
if (imageName)
{
UIImage *image = [UIImage imageNamed:imageName];
if (image)
{
cell.customImageView.image = image;
}
else
{
// Set an empty state here
cell.customImageView.image = [UIImage imageNamed:#"errorImage.png"];
}
}
return cell;
}
In my iPhone app I just parse the JSON from a url and save it to arrays. After completing JSON parsing my UICollectionView should be updated with the new array values. But my UICollectionView isn't updating. Please look through my following coding
#interface SpecialPgms ()
#property (strong, nonatomic) IBOutlet UICollectionView *collecSpecial;
#end
#implementation SpecialPgms
NSMutableArray *arrTitle,*arrUrl,*arrImg;
UICollectionViewCell *cell ;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.collecSpecial.delegate=self;
self.collecSpecial.dataSource=self;
[self loadJSON];
}
-(void)loadJSON{
arrTitle=[[NSMutableArray alloc]init];
arrUrl=[[NSMutableArray alloc]init];
arrImg=[[NSMutableArray alloc]init];
[pro startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
JSONDecoder *decoder = [JSONDecoder decoderWithParseOptions:JKParseOptionStrict];
NSData *immutableItemList = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos?author=jiljilmedia&v=2&alt=jsonc"]];
NSData *data =immutableItemList;
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData* data1 = [string dataUsingEncoding:NSUTF8StringEncoding];
NSArray *returnedData = (NSArray *) [[[decoder objectWithData:data1] objectForKey:#"data"] objectForKey:#"items"];
for(NSDictionary * student in returnedData){
NSString *strTitle=[student objectForKey:#"title"];
NSDictionary *Thumbnail=[student objectForKey:#"thumbnail"];
NSString *strImg = Thumbnail[#"sqDefault"];
NSDictionary *player = student[#"player"];
NSString *strdefaultUrl = player[#"default"];
NSString *strMobileUrl=player[#"mobile"];
[arrTitle addObject:strTitle];
//NSLog(#"%#",strImg);
if(strMobileUrl.length==0){
[arrUrl addObject:strdefaultUrl];
}
else{
[arrUrl addObject:strMobileUrl];
}
[arrImg addObject:strImg];
}
[self performSelectorOnMainThread:#selector(setProgramTableView:) withObject:[NSArray arrayWithObjects: nil] waitUntilDone:YES];
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return arrTitle.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[arrImg objectAtIndex:indexPath.row]];
UILabel *lab = (UILabel *)[cell viewWithTag:101];
lab.text= [arrImg objectAtIndex:indexPath.row];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame.png"]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d",indexPath.row);
}
////// JSON Parsing for video links////////////////////
- (void)setProgramTableView: (NSArray*)array
{
dispatch_async(dispatch_get_main_queue(), ^{
[ self.collecSpecial reloadData];
[ self.collecSpecial.collectionViewLayout invalidateLayout];
});
[pro stopAnimating];
}
I want to connect an my app to the database and display it in a Label.
I could connect my app to the database and display it in the UITableView.
This is what I have so far:
Viewontroller.h
#import <UIKit/UIKit.h>
#interface CartHistoryViewController : UITableViewController
{
NSMutableArray *arrayDataFromServer;
}
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/CartGet.php? choice=history"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
strURL = #"http://localhost:8888/CartGet.php?choice=historydate";
NSArray *arrayImagesPaths = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
// store the result in arrayDataFromServer
arrayDataFromServer = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
NSEnumerator *enumForPahts = [arrayImagesPaths objectEnumerator];
id objName, objPath;
while ( objName = [enumForNames nextObject]) {
objPath = [enumForPahts nextObject];
[arrayDataFromServer addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", objPath, #"path", nil]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"name"];
[cell.textLabel setFont:[UIFont systemFontOfSize:20]];
cell.detailTextLabel.text = [[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"path"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"path"]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
cell.imageView.image = img;
return cell;
}
I want to be able to display it in a Label and in an ImageView instead of a cell. Please help.
Go to your Interface Builder choose your table view and make it Grouped TableView
add below code before your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrayDataFromServer count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
// set header height of gropued tableview
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
return 120;//change this value if it is too big
}
//set header section labels
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSString * subject=[[arrayDataFromServer objectAtIndex:section] objectForKey:#"name"];//this line may give you error because of section easy to correct
UILabel *subjectLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 30, 100, 100)];
subjectLabel.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
subjectLabel.font = [UIFont fontWithName:#"Arial" size:25];
subjectLabel.text = subject;
subjectLabel.backgroundColor = [UIColor clearColor];
[subjectLabel sizeToFit];
// if you want to add image view create an imageview programatically here
// NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[[arrayDataFromServer objectAtIndex:section] objectForKey:#"path"]]];
//NSData *data = [NSData dataWithContentsOfURL:url];
//UIImage *img = [UIImage imageWithData:data];
// UIImageView *brickAnim = [[UIImageView alloc] initWithImage:img];
// Create header view and add label as a subview choose coordinates wisely
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 120, 100, G00)];
[view addSubview:subjectLabel];
//[view addSubview:brickAnim];
return view;
}