UICollectionView Displays empty - ios

Hi in my application in trying display the Flickr images in my UICollectionView but it shows a empty View Control
My code for display the Flickr images.
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoids;
}
viewDidLoad code.
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoids = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
[self.collectionview reloadData];
}
- (void)loadFlickrPhotos {
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&photoset_id=72157644758906604&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [photoids count];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier =#"Cell";
imggpolitical *cell=(imggpolitical *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath: indexPath];
cell.imageview.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoids objectAtIndex:indexPath.row]]]]];
return cell;
}
I have used the above to display the Flickr images in UICollectionView but its coming as a empty view please tell me how to resolve this issue.
Thanks.

At the end of -(void)loadFlickrPhotos method, call reloadData on your UICollectionView. You need to tell UICollectionView to refresh its data.

Try [self.collectionview reloadData]

I don't see that you're assigning a delegate or data source. Or for that matter, created your UICollectionView.

Related

reloadData is stacking ontop of old data

I understand that I need to change the data in the data source before calling reloadData. My problem is that I'm not sure how this is done and why my getData method doesn't overwrite the current cells. Is it necessary to use subviews for this? Or is there a way to reset the cells when refresh is called to just create a new set of data?
#property (nonatomic,strong) NSMutableArray *objectHolderArray;
#end
#implementation MartaViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self getData];
//to add the UIRefreshControl to UIView
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Please Wait..."];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
}
- (void)getData
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:#"station"] Status:[bpDictionary objectForKey:#"status"]];
[self.objectHolderArray addObject:currenHotel];
}
}
- (IBAction)refresh:(UIRefreshControl *)sender {
[self getData];
[self.tableView reloadData];
[sender endRefreshing];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MartaViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
Object *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblStation.text = currentHotel.station;
cell.lblStatus.text = currentHotel.status;
return cell;
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
#end
Because you are adding objects to self.objectHolderArray instead of overwriting in getData method. Try this
- (void)getData
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
[self.objectHolderArray removeAllObjects];
for (NSDictionary *bpDictionary in dataDictionary) {
Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:#"station"] Status:[bpDictionary objectForKey:#"status"]];
[self.objectHolderArray addObject:currenHotel];
}
}
First initialize the array in viewDidLoad self.objectArray = [NSMutlabelArray alloc] init] and when you are refreshing the table view remove all objects from object array using [self.orderArray removeAllObject] the copy new content in new array.

How to show my url json data to collection view

I have get data from one url with authorized header and i convert to json.
In my json i am having only pdf file. But i don't want to show pdf file. I want to show the file name ( eg : document1.pdf, document2.pdf ).and also i am having 3 section - each contain 10 documents. So i need to show name of the document.
I saw some tutorials which using only image not document file. So how to show my document name alone to collection view.
One more question. does i need to decode to show my data or don't want to do that. Help me out.Thanks in advance !
NSMutableArry *arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = [jsonResultsvalueForKey:#"original"];
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int i=0;i<[arrayFiles count];i++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}
in collectionview you need use the above arrayPDFName(in collection view delegates methods)
Showing data in CollectionView
- (void)viewDidLoad
{
[super viewDidLoad];
[self getResponse];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//Register the custom cell for collection view
UINib *cellNib = [UINib nibWithNibName:#"CustomCell" bundle:nil];
[collectionViewHorizontalVertical registerNib:cellNib forCellWithReuseIdentifier:#"cvCell"];
}
//Collection View Delegates method
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrayPDFName.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cvCell";
CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
//data for text
cell.textField.text = [arrayPDFName objectAtIndex:indexPath.row];
//OR Image
cell.imgViewCollection.image = [UIImage imageNamed:[arrayPDFName objectAtIndex:indexPath.row]];
return cell;
}
// If you want to set the cell height
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(200, 200); //Please give your required size
}

UITableView Scroll Lag

I have a UITableView that loads content from a server.
All works fine and the content loads correctly, but when I scroll my UITableView lags a bit.
I created a method that downloads the content from a server, and I call this method in my viewDidLoad method, since it is the first thing that opens when I open the app.
I don't know if this is the best approach.
How I can avoid that? Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Method that Loads the Content
[self retrieveData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Retorna o nĂºmero de linhas pelo array de programacao.
return programacaoArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// ALTURA da TableViewCell
return 150;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"CellIdentifier";
ProgramacaoTableCell *cell = (ProgramacaoTableCell *)[self.tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[ProgramacaoTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
// Configure the Cell
Programacao *programacaoObject;
programacaoObject = [programacaoArray objectAtIndex:indexPath.row];
cell.atracaoImagem.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:programacaoObject.programacaoImagem]]];
cell.nomeLabel.text = programacaoObject.programacaoNome;
cell.dataLabel.text = programacaoObject.programacaoData;
cell.localLabel.text = programacaoObject.programacaoLocal;
return cell;
}
- (void) retrieveData
{
NSURL *url = [NSURL URLWithString:getDataURL];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// SETUP programacaoArray
programacaoArray = [[NSMutableArray alloc] init];
// Loop throught do Array
for (int i = 0; i < jsonArray.count; i++) {
// Cria o PROGRAMACAO Objeto
NSString *pID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *pNome = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoNome"];
NSString *pImagem = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoImagem"];
NSString *pDescricao = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoDescricao"];
NSString *pData = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoData"];
NSString *pLocal = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoLocal"];
NSString *pPrecos = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoPrecos"];
// Add to the Array
[programacaoArray addObject:[[Programacao alloc] initWithNome:pNome andImagem:pImagem andDescricao:pDescricao andData:pData andLocal:pLocal andPrecos:pPrecos andID:pID]];
}
// RELOAD TABLE VIEW
[self.tableView reloadData];
}
There's a very obvious mistake you're making. You're loading the image synchronously (on the same thread, which in this case is the main thread), which is what's causing the lag. You should look into using AFNetworking's UIImageView category, which will load these images in the background for you.
You can download the AFNetworking library from here.
I think cause problem by code:
'cell.atracaoImagem.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:programacaoObject.programacaoImagem]]];
you can use SDWebImage framework, loading image
I think you should call the retrieveData function in viewWillAppear method instead of viewDidLoad

how to do multi-threading to load the image faster to tableView

-(void)viewDidLoad {
[super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.navigationItem.title = #"New Arrivals";
[super viewDidLoad]; idsArray=[[NSMutableArray alloc]init]; namesArray=[[NSMutableArray alloc]init]; imagesArray=[[NSMutableArray alloc]init];
// create the URL we'd like to query
NSURL *myURL = [[NSURL alloc]initWithString:#"http://www.bikrionline.com/nwarvl-json.php"];
// we'll receive raw data so we'll create an NSData Object with it NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
// now we'll parse our data using NSJSONSerialization if ([myData length]>0) { id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil]; NSArray *jsonArray = (NSArray *)myJSON; for (int i=0 ; i<[jsonArray count] ; i++) { NSMutableString *urlString = [[NSMutableString alloc]initWithString:#"http://www.bikrionline.com/products/zmphotos/"]; NSString * name = [[[jsonArray objectAtIndex:i]objectForKey:#"prodname"]retain]; [namesArray addObject:name]; [idsArray addObject:[[jsonArray objectAtIndex:i]objectForKey:#"prodid"]]; [urlString appendString:[[jsonArray objectAtIndex:i]objectForKey:#"imageurl"]]; UIImage *imageObj = [self getImageFromUrl:urlString]; urlString = nil; [imagesArray addObject:imageObj]; } }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCellView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *arrNib = [[NSBundle mainBundle] loadNibNamed:#"CustomCellView" owner:self options:nil];
cell = [arrNib objectAtIndex:0];
}
cell.imgName.text = [namesArray objectAtIndex:indexPath.row];
cell.custImageView.image=[imagesArray objectAtIndex:indexPath.row];
return cell;
}
You can use some Lib like SDWebImage or Afnetworking. Libs support lazy load image and auto cache this image.
All you need to do:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"url of image"]
placeholderImage:nil];
This is looking a similar question like lazy loading of an image: Check iOS lazy-loading of table images and Loading images on scrollview using lazy loading
for your answer

Warning where I cannot clear [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an error saying Incompatible pointer types sending NSArray to parameter of NSString. I also have used instruments and is very weird that as soon as my app start its around 90mb in memory. What is wrong with my code.
#interface TrashViewController ()
#end
#implementation TrashViewController {
NSMutableArray *Trash ;
}
#synthesize collectionTrash;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
filenames = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *locations = [[NSArray alloc]initWithObjects:#"Bottoms", #"Dress", #"Coats", #"Others", #"hats", #"Tops",nil ];
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:locations];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionTrash.delegate =self;
collectionTrash.dataSource=self;
for(NSString *str in directoryContent)
{
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
[filenames addObject:finalFilePath];
}
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
NSLog(#"j");
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [filenames count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"ReuseID";
TrashCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[cell viewWithTag:1];
NSString *cacheKey = filenames[indexPath.item];
imageInCell.image = [self.imageCache objectForKey:cacheKey];
if (imageInCell.image == nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [UIImage imageWithContentsOfFile:filenames[indexPath.item]];
if (image) {
[self.imageCache setObject:image forKey:cacheKey];
dispatch_async(dispatch_get_main_queue(), ^{
TrashCell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[updateCell viewWithTag:1];
imageInCell.image = image;
});
}
});
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"s:%d", [Trash count]);
NSString *trashBin = [Trash objectAtIndex:indexPath.row];
NSLog(#"k%#l",trashBin);
[filenames removeObjectAtIndex:indexPath.row];
[Trash removeObjectAtIndex:indexPath.row];
[self deleteMyFiles:trashBin];
[collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]];
}
NSString *myFileName;
-(void) deleteMyFiles:(NSString*)filePath {
NSError *error;
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
} else {
NSLog(#"%#",filePath);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
[self.imageCache removeAllObjects];
}
eYour problem is in line 5 of viewDidLoad. The method signature for -stringByAppendingPathComponent is
- (NSString *)stringByAppendingPathComponent:(NSString *)aString
Note that it expects a String, but you are passing an Array.
What you probably want to do is change
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:locations];
To something like
NSInteger someIndex = 0; //this will pick the first object in locations, e.g. #"Bottoms".
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:[locations objectAtIndex:someIndex]];
locations is an Array of Strings, so you need to pick one and not pass the entire Array.
Also, next time please dont just dump your code in here, but tell us which line caused the error. You are much more likely to get a quick response if you can point to the part that couses the problems.

Resources