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

-(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

Related

how to load more data in the tableview when the tableview reaches its last row in objective c?

im trying to do load more data of an api when the tableview reaches its last row using its page number in the api like instagram feed....I need help to resolve this...could somebody help me with the code...
I need to know that whether I have to keep one method for loading data from json and also have the same method for load more data?
2.if I run my code im getting the 1st page data correctly and the second page has only one record but whenever the tableview is scrolling from the last row of the tableview it is displaying multiple time.
could somebody please help me to do this...
Here im fetching my json data in
-(void)fetch data
NSString *urlstring = #"https://bsedemo.com/instasocial/api/post/feeds?user_id=402&&access_token=$2y$10$TWX2Ym1gM4NBjGCNzTydzuQTZWPcK2tMVw1eWdWvYDFmO4CsKc1kC&&page_no=1&&feed_type=3&&feed_id=&&member_id=402";
NSURL *url =[NSURL URLWithString:urlstring];
NSData *url_data = [[NSData alloc]initWithContentsOfURL:url];
NSDictionary *loaded_jsondata_dict = [NSJSONSerialization JSONObjectWithData:url_data options:NSJSONReadingAllowFragments error:nil];
data_values = [[NSMutableArray alloc]init];
for(dict in [loaded_jsondata_dict objectForKey:#"result"])
{
[data_values addObject:dict];
}
[tableview reloadData];
here is my table view cell
cellForRowAtIndexPath
static NSString *simpleTableIdentifier = #"Cell";
TableViewCellVC *cell = [[TableViewCellVC alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
cell=[tableview dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
media= [[NSMutableArray alloc]init];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCellVC" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.profileImageView.layer.cornerRadius = 23.5;
cell.profileImageView.image = [UIImage imageNamed:#"girl1.jpg"];
cell.usernameLabel.text= [[data_values objectAtIndex:indexPath.row]valueForKey:#"user_name"];
cell.lastseenLabel.text =[[data_values objectAtIndex:indexPath.row]valueForKey:#"created_at"];
cell.commentcount.text =[[[data_values objectAtIndex:indexPath.row]valueForKey:#"post_comment_count"]stringValue];
cell.likecount.text =[[[data_values objectAtIndex:indexPath.row]valueForKey:#"post_like_count"]stringValue];
cell.discriptionLabel.text =[[data_values objectAtIndex:indexPath.row]valueForKey:#"post_text"];
media =[[data_values objectAtIndex:indexPath.row]valueForKey:#"media"];
media_dict = media[0];
NSString *media_urlstring =[media_dict valueForKey:#"media_name"];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL *media_url =[NSURL URLWithString:media_urlstring];
NSData *url_data = [[NSData alloc]initWithContentsOfURL:media_url];
dispatch_sync(dispatch_get_main_queue(), ^{
cell.postImageView.image = [UIImage imageWithData:url_data];
});
});
media_height = [[media_dict valueForKey:#"media_height"]floatValue];
media_width =[[media_dict valueForKey:#"media_width"]floatValue];
CGFloat screensize = [UIScreen mainScreen].bounds.size.height;
cell_height =(((screensize/media_height)*media_width)-340);
return cell;
here is my load more data method and scrollviewdidscroll method
-(void)loadmoredata
NSString *urlstring = #"https://bsedemo.com/instasocial/api/post/feeds?user_id=402&&access_token=$2y$10$TWX2Ym1gM4NBjGCNzTydzuQTZWPcK2tMVw1eWdWvYDFmO4CsKc1kC&&page_no=2&&feed_type=3&&feed_id=&&member_id=402";
NSURL *url =[NSURL URLWithString:urlstring];
NSData *url_data = [[NSData alloc]initWithContentsOfURL:url];
NSDictionary *loaded_jsondata_dict = [NSJSONSerialization JSONObjectWithData:url_data options:NSJSONReadingAllowFragments error:nil];
data_values_2 = [[NSMutableArray alloc]init];
for(NSDictionary *page2_dict in [loaded_jsondata_dict objectForKey:#"result"])
{
[data_values_2 addObject:page2_dict];
}
if(data_values.count-1)
{
[data_values addObjectsFromArray:data_values_2];
}
[activity_indicator stopAnimating];
[tableview reloadData];
scrollviewdidscrollmethod
scrollviewdidscrollmethod
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
int scrollViewContentHeight = tableview.contentSize.height;
int scrollOffset = scrollViewContentHeight -tableview.bounds.size.height;
if(scrollView.contentOffset.y > scrollOffset && tableview.isDragging)
{
CGRect frame = CGRectMake(0,tableview.contentSize.height,tableview.bounds.size.width,60);
activity_indicator.frame = frame;
[activity_indicator startAnimating];
[self loadMoreData];
}

UICollectionView Displays empty

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.

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 set tableView cell title in ios?

I am parsing JSON and storing it in an array.I have a custom cell subclass in which I am trying to set the title of a label from the content of parsed JSON.
This is the parsing process.
#implementation BlogScreenViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.jsonArray = [[NSMutableArray alloc]init];
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#"http:web_services/blog.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
for (NSDictionary *obj in self.jsonArray)
{
NSLog(#"JSON string output :- %# ", [obj objectForKey:#"titre"]); // shows titles
}
In custom cell subclass
// set blog title label
UILabel *blogTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 20, 200, 20)];
// blogTitleLabel.text = #"This is blog title"; // This shows properly if used.
for (NSDictionary *obj in blogScreenVC.jsonArray ) //This doesn't work.
{
blogTitleLabel.text = [NSString stringWithFormat:#"%#",[obj objectForKey:#"titre"]];
}
[blogTitleLabel setFont:[UIFont systemFontOfSize:9]];
[self addSubview:blogTitleLabel];
Instead of Setting lebel.text in customcell class add it in the cellForRowAtIndexPath.
Create Property of label in customcell.h file
#property (nonatomic, weak) IBOutlet UILabel *label;
And in customcell.m file synthesys it.
#synthesize label = _label;
And in you viewcontroller.m file
#import "CustomCell.h"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (self.jsonArray.count !=0) {
NSMutableDictionary * tmpDictn = [self.jsonArray objectAtIndex:indexPath.row];
if ([tmpDictn objectForKey:#"titre"] != nil)
{
cell.label.text = [tmpDictn objectForKey:#"titre"];
}else{
cell.label.text = #"tmpDictn does not contain data";
}
}else{
cell.label.text = #"jsonArray does not contain data";
}
return cell;
}

Parsing JSON url pictures to iOS not working

I'm trying to parse a json-file containing links to images. This is my code:
#import "Pictures.h"
#import "DEMONavigationController.h"
#import "PicturesObject.h"
#interface Pictures ()
{
NSInteger refreshIndex;
NSArray *images;
NSMutableArray *jsonIs;
NSArray *items;
IBOutlet UIImageView *imagesinsta;
}
#end
#implementation Pictures
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Pictures";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu"
style:UIBarButtonItemStylePlain
target:(DEMONavigationController *)self.navigationController
action:#selector(showMenu)];
// ***************** FETCHING DATA ******************* //
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"link-to-json.php?image=Image"]];
NSData *data= [NSData dataWithContentsOfURL:URL];
if (data == nil) {
return;
}
NSError* error;
items = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",jsonIs);
if (jsonIs != nil) {
NSMutableDictionary* aDict = jsonIs[0];
NSString *item_media = [aDict objectForKey:#"link"];
}
// ***************** FETCHING DATA ******************* //
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PicturesObject";
PicturesObject *cell = (PicturesObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PicturesObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *item = [items objectAtIndex:indexPath.row];
NSString *item_media = [item objectForKey:#"link"];
return cell;
}
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"link-to-json.php?image=Image"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
// going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data.
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
#end
This is how my custom PicturesObject table view look like:
But when I launch my app I only get a screen like this:
Json Data is similar to Dictionary and not an array. Instead of using
NSArray items
use
NSDictionary items
and then extract the the relevant data from dictionary.

Resources