Action on Section Header Tableview iOS - ios

I've a view in Section Header where I placed a Button over it. On that button click API hits but the section index picked is wrong,
I want to send Object at the Section Header index as parameter.
Here is my code for Tableview:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[DATAA objectAtIndex:section] objectForKey:#"subitemname"];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *aView =[[UIView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 40)];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTag:section+1];
[aView addSubview:btn];
[btn addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchDown];
UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x+20, btn.frame.origin.y, btn.frame.size.width, btn.frame.size.height)];
title.text=[[DATAA objectAtIndex:section] objectForKey:#"subitemname"];
title.font=[UIFont boldSystemFontOfSize:12.0];
title.textColor=[UIColor grayColor];
[aView addSubview:title];
indexx=[[DATAA objectAtIndex:section] objectForKey:#"subitemid"];
NSLog(#"indexL:%#",indexx);
return aView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [DATAA count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat height = 30;
return height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *subMenuData = [[DATAA objectAtIndex:section] objectForKey:#"Submenu"];
return [subMenuData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell=[tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary *cellData = [[[DATAA objectAtIndex:indexPath.section] objectForKey:#"Submenu"] objectAtIndex:indexPath.row];
cell.textLabel.text=[cellData objectForKey:#"subtosubitemname"];
cell.textLabel.font=[UIFont boldSystemFontOfSize:12.0];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (void)sectionTapped:(UIButton*)btn {
NSString *urlString = [NSString stringWithFormat:#"http://URL/api/SearchItem?subitemid=%#",indexx];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"json:%#",jsonDict);
}

do like this.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[DATAA objectAtIndex:section] objectForKey:#"subitemname"];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *aView =[[UIView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 40)];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTag:section+1];
[aView addSubview:btn];
[btn addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchDown];
UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x+20, btn.frame.origin.y, btn.frame.size.width, btn.frame.size.height)];
title.text=[[DATAA objectAtIndex:section] objectForKey:#"subitemname"];
title.font=[UIFont boldSystemFontOfSize:12.0];
title.textColor=[UIColor grayColor];
[aView addSubview:title];
//indexx=[[DATAA objectAtIndex:section] objectForKey:#"subitemid"];
//NSLog(#"indexL:%#",indexx);
return aView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [DATAA count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat height = 30;
return height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *subMenuData = [[DATAA objectAtIndex:section] objectForKey:#"Submenu"];
return [subMenuData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell=[tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary *cellData = [[[DATAA objectAtIndex:indexPath.section] objectForKey:#"Submenu"] objectAtIndex:indexPath.row];
cell.textLabel.text=[cellData objectForKey:#"subtosubitemname"];
cell.textLabel.font=[UIFont boldSystemFontOfSize:12.0];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (void)sectionTapped:(UIButton*)btn {
NSString *urlString = [NSString stringWithFormat:#"http://dealnxt.com/api/SearchItem?subitemid=%#",btn,tag];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"json:%#",jsonDict);
}

You are keeping the variable indexx as global variable, so if we scroll the tableView, then the variable get update. So it is not a good approach. Please update your 2 methods like mentioned below
Method: 1
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *aView =[[UIView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 40)];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTag:section+1];
[aView addSubview:btn];
[btn addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchDown];
UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x+20, btn.frame.origin.y, btn.frame.size.width, btn.frame.size.height)];
title.text=[[DATAA objectAtIndex:section] objectForKey:#"subitemname"];
title.font=[UIFont boldSystemFontOfSize:12.0];
title.textColor=[UIColor grayColor];
[aView addSubview:title];
return aView;
}
Method 2:
- (void)sectionTapped:(UIButton*)btn {
indexx=[[DATAA objectAtIndex:btn.tag - 1] objectForKey:#"subitemid"];
NSString *urlString = [NSString stringWithFormat:#"http://dealnxt.com/api/SearchItem?subitemid=%#",indexx];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"json:%#",jsonDict);
}

Related

UITableViewCell stored in other array

I have one array(arrData) and UITableViewCell reload arrData. arrData stored in web service array of objects.
UITableViewCell in a two label and one image, label and image load data by arrData. so all label and image reload in same array but i want to reload different-different array each label and image.
ViewController
#import "ViewController.h"
#import "MemberTableViewCell.h"
#import "member_details.h"
#interface ViewController ()
{
NSArray *arrData;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tabel_view setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *status = json[#"status"];
arrData = status;
[self.tabel_view reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray<NSIndexPath *> *selectedRows = [tableView indexPathsForSelectedRows];
if (selectedRows && [selectedRows containsObject:indexPath]) {
return 127.0; // Expanded height
}
return 50.0; // Normal height
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.name.text= [[arrData objectAtIndex:indexPath.row] valueForKey:#"business_category_name"];
cell.title.text= [[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"name"];
cell.email.text=[[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"email"];
cell.image_view.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[[arrData objectAtIndex:indexPath.row]valueForKey:#"business_details"]objectAtIndex:0] valueForKey:#"img_url"]]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[self.tabel_view beginUpdates];
[self.tabel_view endUpdates];
}
#end
try this code
#import "ViewController.h"
#interface ViewController ()
{
IBOutlet UITableView *tbl;
NSMutableData *response;
NSMutableArray *Arrdata;
NSMutableArray *ArrySubData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
Arrdata=[[NSMutableArray alloc]init];
ArrySubData=[[NSMutableArray alloc]init];
[tbl setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *status = json[#"status"];
Arrdata = status;
NSLog(#"%#",Arrdata);
[tbl reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
ArrySubData=[[Arrdata objectAtIndex:section] objectForKey:#"business_details"];
return ArrySubData.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [NSString stringWithFormat:#" %#",[[Arrdata objectAtIndex:section] objectForKey:#"business_category_name"]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *myLabel = [[UILabel alloc] init];
myLabel.frame = CGRectMake(0, 0, 320, 20);
myLabel.font = [UIFont fontWithName:#"Roboto-Bold" size:13.0];
myLabel.textColor=[UIColor whiteColor];
myLabel.backgroundColor=[UIColor colorWithRed:70.0/255.0 green:82.0/255.0 blue:88.0/255.0 alpha:1.0];
myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *ImgBrands = (UIImageView *) [cell viewWithTag:101];
UILabel *lblName = (UILabel *) [cell viewWithTag:102];
UILabel *lblEmail = (UILabel *) [cell viewWithTag:103];
UILabel *lblPhone = (UILabel *) [cell viewWithTag:104];
ArrySubData=[[Arrdata objectAtIndex:indexPath.section] objectForKey:#"business_details"];
NSString *strName=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"name"]];
NSString *stremail=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"email"]];
NSString *strphone=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"phone"]];
NSString *strimage=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"image"]];
lblName.text=strName;
lblEmail.text=stremail;
lblPhone.text=strphone;
ImgBrands.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strimage]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[tbl beginUpdates];
[tbl endUpdates];
}

Data from JSON not updating in UICollectionView

I'm creating an app with a Newsfeed as a UICollectionView however it doesn't seem to update when I change the JSON file. I am using a UIRefreshControl to refresh it but I can't tell if my issue is to do with this or to do with how the JSON is read (or something else entirely).
viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationItem.title = #"News";
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,23,16);
[btn setBackgroundImage:[UIImage imageNamed:#"menuImage.png"] forState:UIControlStateNormal];
[btn addTarget:(NavigationViewController *)self.navigationController action:#selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = barBtn;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
[self fetchFeed];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat frameWidth = screenRect.size.width - 20;
CGFloat frameHeight = screenRect.size.height - 20;
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(10, 10, frameWidth, frameHeight) collectionViewLayout:layout];
[_collectionView setDataSource: self];
[_collectionView setDelegate: self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:_collectionView];
UIRefreshControl * refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Refresh Images"];
[_collectionView addSubview:refreshControl];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
[self.collectionView reloadData];
}
fetchFeed
- (void)fetchFeed
{
NSString *requestString = #"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.articles = jsonObject[#"articles"];
NSLog(#"%#", self.articles);
NSLog(#"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{[self.collectionView reloadData];
});
}];
[dataTask resume];
}
refresh
- (void)refresh:(id)sender
{
[self fetchFeed];
[(UIRefreshControl *)sender endRefreshing];
NSLog(#"Refreshed");
}
Any help will be really appreciated.
Collection View Data Source
#define LABEL_TAG 100001
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *articleTitle = [cell.contentView viewWithTag:LABEL_TAG];
NSDictionary *article = self.articles[indexPath.row];
if (!articleTitle) {
articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(5, cell.bounds.size.height - cell.bounds.size.height / 2.2, cell.bounds.size.width - 10, cell.bounds.size.height / 2)];
articleTitle.textColor = [UIColor whiteColor];
articleTitle.numberOfLines = 3;
articleTitle.adjustsFontSizeToFitWidth = YES;
articleTitle.tag = LABEL_TAG;
[cell.contentView addSubview:articleTitle];
}
articleTitle.text = article[#"title"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[#"image"]]];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
[bgImageView setContentMode:UIViewContentModeScaleAspectFill];
[bgImageView setClipsToBounds:YES];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, cell.bounds.size.height - cell.bounds.size.height / 2, cell.bounds.size.width, cell.bounds.size.height/2);
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
//gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:0.5], nil];
[bgImageView.layer insertSublayer:gradient atIndex:0];
cell.backgroundView = bgImageView;
return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 10; // This is the minimum inter item spacing, can be more
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
int x = screenWidth/2 - 15;
int y = x;
return CGSizeMake(x, y);
}
- (void)collectionView:(UICollectionView *)colView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
NSDictionary *article = self.articles[indexPath.row];
NSURL *URL = [NSURL URLWithString:article[#"url"]];
self.webViewController.title = article[#"title"];
self.webViewController.URL = URL;
[self.navigationController pushViewController:self.webViewController
animated:YES];
}
If NSLog(#"%#", self.articles) works and shows data you have proven that you are getting network data back. Did you set up your UIView as the delegate and the datasource properly? This is usually done at the top of the UIViewController class and looks like this:
class MyClassName: UICollectionViewDataSource {
// Your code here.
}
One way to check if the datasource is set up correctly is to set a breakpoint here
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
print(“This shows that I’m getting called”)
// Your custom code
}
When you call
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
})
this will in turn call cellForItemAtIndexPath to display data. If cellForItemAtIndexPath isn’t called then you have not properly set your UICollectionViewDataSource
Try to this
- (void)fetchFeed {
NSString *requestString = #"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest*req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask*dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.articles = jsonObject[#"articles"];
NSLog(#"%#", self.articles);
NSLog(#"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{
[_collectionView reloadData];
});
}];
[dataTask resume];
}

UITableView taking lots of time to bind data

I am using UITableView and after calling web service I am creating cells and binding data. Web service fetching data speed is very good and fast but i checked it's taking time to bind cells to UITableView.My code is -
.m file
#pragma mark tableViewDelegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return ([team1Arr count]+1);
if (isFiltered) {
return [filteredMySquareArr count];
}
else
return [mySquareArr count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *squareNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(25.0, 7.0, 300, 25)];
[squareNameLbl setFont:[UIFont systemFontOfSize:15]];
UILabel *descLbl = [[UILabel alloc]initWithFrame:CGRectMake(25.0, 32.0, 285.0, 13.0)];
[descLbl setFont:[UIFont systemFontOfSize:12]];
descLbl.textColor = [UIColor colorWithRed:72.0f/255 green:180.0f/255 blue:71.0f/255 alpha:1.0f];
UIImageView *lockImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 10, 10)];
NSString *accessTypeStr;
if (isFiltered) {
//cell.textLabel.text = [filteredMySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [filteredMySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles", [[filteredMySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[filteredAccessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
else
{
//cell.textLabel.text = [mySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [mySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles",[[mySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[accessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
cell.backgroundColor = [UIColor clearColor];
[cell addSubview:squareNameLbl];
[cell addSubview:descLbl];
[cell addSubview:lockImage];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
[image setImage:[UIImage imageNamed:#"arrow_list.png"]];
cell.accessoryView = [[UIImageView alloc]initWithFrame:CGRectMake(260.0, 7.0, 10, 20)];
[cell.accessoryView addSubview:image];
});
// });
//cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"arrow_list.png"]];
return cell;
}
WebService
#pragma mark - Webservice Methods
-(void)fetchUpcomingSquares
{
NSString *post = [NSString stringWithFormat:#"access_token=%#&page=0",globalAccessToken];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upcoming_squares",GLOBALURLDOMAIN]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLResponse *response;
NSError *error =nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"responsedata =%#",responseData);
if(error)
{
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
[hud hide:YES];
return;
}
if (responseData == NULL) {
AppDelegate *appdel = [[UIApplication sharedApplication]delegate];
[hud hide:YES];
[appdel alertError];
}
else
{
NSDictionary *parsingResultLogin = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"parsingResultLogin = %#",parsingResultLogin);
if ([#"-1" isEqualToString:[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_code"]]) {
NSLog(#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]);
[self showAlertWithMessage:[NSString stringWithFormat:#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]]];
[hud hide:YES];
}
else
{
NSLog(#"Valid ID");
NSDictionary *result= [parsingResultLogin objectForKey:#"result"];
//NSLog(#"result = %#", result);
squareList = [result objectForKey:#"squares"];
NSLog(#"squareList = %#", squareList);
for (NSDictionary *sq in squareList) {
[mySquareArr addObject:[sq objectForKey:#"square_name"]];
[mySquareDescArr addObject:[sq objectForKey:#"max_distance"]];
[accessTypeArr addObject:[sq objectForKey:#"access_type"]];
}
[self.mySquareTblView reloadData];
[hud hide:YES];
}
}
});
NSLog(#"access Type =%#",accessTypeArr);
}
I think it's pretty clear. You're not using your cell identifier on this line of code:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
You should do it like this:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
I used bellow code and it's working fine
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];

How can I add load more in UITableView [duplicate]

This question already has answers here:
How to implement "Load 25 More" in UITableViewController
(4 answers)
Closed 9 years ago.
Can you help me about load more UITableView? I use load more methods, but all records returns instead of 25.What is wrong in code? please help :S Thanks for replying
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad{
itemArray = [[NSMutableArray alloc] init];
[self ServiseBaglan];}
- (void)ServiseBaglan{
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SOAP-ENV:Envelope \n"
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n"
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n"
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n"
"<SOAP-ENV:Body> \n"
"<OnemliYer xmlns=\"http://tempuri.org/\">\n"
"<station>%#</station>\n"
"<dilId>%#</dilId>\n"
"</OnemliYer> \n"
"</SOAP-ENV:Body> \n"
"</SOAP-ENV:Envelope>\n", izmir , #"1"];
NSURL *url = [NSURL URLWithString:#"http://www.manavgatportal.com/Service1.svc"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/IService1/OnemliYer" forHTTPHeaderField:#"Soapaction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
// NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
if(theConnection) {
// webData = [[NSMutableData data] retain];
webData = [[NSMutableData data]init];
}
else {
NSLog(#"theConnection is NULL");
}
[self.tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath{
return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
if ([itemArray count] >= 25) {
count= [itemArray count] + 1;
NSLog(#": %d", count);
}else
{
count=[itemArray count];
NSLog(#": %d", count);
}
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSString *CellIdentifier2 = #"Cell2";
static NSInteger TitleTag = 2;
static NSInteger AddresseTag = 1;
UITableViewCell *cell;
if (indexPath.row != [itemArray count] ) {
cell= (UITableViewCell *) [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
NSDictionary *Item = [itemArray objectAtIndex:indexPath.row];
UIFont *font = [UIFont fontWithName:#"Arial" size:14];
cell.textLabel.font = font;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.numberOfLines = 2;
cell.textLabel.text = [Item objectForKey:#"a:Ad"];
cell.detailTextLabel.text = [Item objectForKey:#"a:Ilce"];
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
}
else {
if(indexPath.row == count-1)
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
}
UILabel *loadMore =[[UILabel alloc]initWithFrame: CGRectMake(0,0,320,30)];
loadMore.textColor = [UIColor blackColor];
loadMore.highlightedTextColor = [UIColor darkGrayColor];
loadMore.backgroundColor = [UIColor clearColor];
loadMore.font=[UIFont fontWithName:#"Verdana" size:14];
loadMore.textAlignment=UITextAlignmentCenter;
loadMore.font=[UIFont boldSystemFontOfSize:14];
loadMore.text=#"load More...";
[cell addSubview:loadMore];
}
}
return cell;
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
I do not think it is good design to redefine your count variable in numberOfRowsInSection.
Rather, you should do this where you actually change the itemsArray. A good place is during the initialisation of the view, and after pressing "load 25 more".
Also, you could consider eliminating the variable altogether and using itemArray.count+1 instead.

Parsing multiple jSon in IOS

For my code, I am following instruction on this link http://www.youtube.com/watch?v=RJZcD3hfs3k and success,
but I want to modify to multiple JSON and failed (if i print log, that its running).
I modify in:
- (void)viewDidLoad
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
This is my modified code(ViewController.m) :
#import "ViewController.h"
#import "DetailViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
//[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//before
//NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
//after
NSURL *url = [NSURL URLWithString:#"http://service.berisiknews.com/article/byAll/0/3"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//before
//news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
//[mainTableView reloadData];
//ßNSLog(#"array %#", news);
//after
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
NSArray *news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete please make sure you're connected to either 3G or Wi-Fi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberINSectionsInTableView: (UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
//return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
//cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"date_string"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"category_name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Any help?
Your news array is a local variable as your code.
In connectionDidFinishLoading, please modify as below
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
so it will be the right news array which your are accessing in table view.
it works fine for me.
#interface AlbumViewController ()
#end
#implementation AlbumViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//navigation Controller
[self.navigationController setNavigationBarHidden:NO];
self.title=#"Album List";
//json data parsing
NSURL *url = [NSURL URLWithString:#".......your Link......"];
NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil];
dict_data = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.ary_data = [dict_data objectForKey:#"album"];
NSLog(#"%#",self.ary_data);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [ary_data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#""];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
AlbumCellController *albumCell = [[AlbumCellController alloc]init];
[cell.contentView addSubview:albumCell.view];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
albumCell.Img_album.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:#"cover_photo"]]]];
});
albumCell.lbl_name.text = [dic objectForKey:#"title"];
albumCell.lbl_releasedate.text = [dic objectForKey:#"release_date"];
NSString *SongNo=[dic objectForKey:#"no_of_songs"];
NSLog(#"%#",SongNo);
//albumCell.lbl_songno.text=SongNo;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
SongsViewController *songList = [[SongsViewController alloc]init];
songList.imgURL = [dic objectForKey:#"cover_photo"];
songList.Album_id = [dic objectForKey:#"album_id"];
[self.navigationController pushViewController:songList animated:YES];
}

Resources