How to populate UITableView with JSON data? - ios

I'm struggling to figure out what i am doing wrong. I am basically trying to populate the my UITableView with json data. In the console I can see the results but just don't know why the data is not displayed in the tableview. I have looked at similar questions and answers but none is a solution to my problem.
Advice or help please;
#pragma mark - Private method implementation
-(void)loadData{
// Form the query.
#try {
NSString *get =[[NSString alloc] initWithFormat:#""];
NSString *getRegions = [NSString stringWithFormat:#"JSON URL HERE",self.sessionId, self.companyId];
NSURL *url=[NSURL URLWithString:getRegions];
NSLog(#"Get regions: %#", url);
NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Reponse code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
#try{
NSError *error = nil;
regionsJson = [[NSMutableArray alloc]init];
//[jsonData removeAllObjects];
regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];
NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
}
#catch (NSException *e){
NSLog(#"Try catch block: %#", e);
}
#finally{
// [self.tblRegion reloadData];
NSLog(#"finally");
}
structureJson =[regionsJson valueForKey:#"structure"];
companyJson =[structureJson valueForKey:#"company"];
_barBtnCompanyName.title = [companyJson valueForKey:#"company_name"];
NSLog(#"Get company name: %#", [companyJson valueForKey:#"company_name"]);
for (int i =0 ; i < regionsJson.count; i++){
regionsJson = [companyJson objectForKey:#"regions"];
NSString *regionName = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"region_name"]];
NSLog(#"Region name: %#",regionName);
// [regionsJson addObject:regionName];
NSString *alarmCount = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"alarm_cnt"]];
NSLog(#"Alarm count: %#", alarmCount);
// [regionsJson addObject:alarmCount];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
// Reload the table view.
[self.tblRegion reloadData];
}
#pragma mark - UITableView method implementation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"Number of rows: %lu", (unsigned long)regionsJson.count);
return [regionsJson count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellRegions";
// Dequeue the cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set the loaded data to the appropriate cell labels.
cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"region_name"];
cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"alarm_cnt"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
NSLog(#"Table cell: %#", cell);
return cell;
}

My code is just fine, i did a stupid omission of this declaration.
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
[self loadData];
}

Related

How to maintain two custom cells in one tableview with segment selection?

I am new to iOS. I have one UIViewController in that added one tableview and segmented control. If I press the segmented value = 0, I want to the first custom cell with loading images and title and segment value = 1, I want to display my second custom cell with UICollectionView with loading of images and title, how can I do that please help me? Here is some of my code:
MenuViewController.m
-(void)callSegmentSelected
{
value=(int)segment.selectedSegmentIndex;
if (segment.selectedSegmentIndex == 0)
{
NSString *urlString = [NSString stringWithFormat:#"http://API"];
NSString *jsonString = #"";
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
listBannerArray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[progressHud hide:YES];
[self.tableViewContest reloadData];
}
else
{
NSLog(#"Error");
}
}
Here is my CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"Cell";
MenuTableViewCell *cell = (MenuTableViewCell *)[tableViewContest dequeueReusableCellWithIdentifier:cellId];
if (cell == nil)
{
NSArray * myNib;
myNib =[[NSBundle mainBundle]loadNibNamed:#"MenuTableViewCell" owner:self options:nil];
cell = (MenuTableViewCell *)[myNib lastObject];
}
if(value == 0)
{
#try
{
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] length] > 0)
{
NSURL *imageURL = [NSURL URLWithString:[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"]];
[cell.listBanner sd_setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"profilepic_bg"]];
}
else
{
}
}
}
#catch (NSException *exception)
{
}
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] length] > 0)
{
cell.examTitle.text = [[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"];
}
else
{
cell.examTitle.text = #"Data Error";
}
}
else
{
cell.examTitle.text = #"Data Error";
}
}
When Click on SegmentIndex=0 Screen like this
When Click on SegmentIndex=1 like this
You can create the enum for differentiate the segment action.
Step 1 : Create the enum for the selection.
typedef enum {
OPTION_FIRST = 0,
OPTION_SECOND
} SEGMENT_SELECTION;
Step 2 : On your MenuViewController.m
1) Create the instance of SEGMENT_SELECTION
#property(nonatomic) SEGMENT_SELECTION segmentSelection;
2) Assign the value to segmentSelection
-(void)callSegmentSelected
{
if (segment.selectedSegmentIndex == 0)
segmentSelection = OPTION_FIRST
else
segmentSelection = OPTION_SECOND
[self.tableViewContest reloadData];//For update the content in tableview
}
Step 3 : Write the below code on CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(segmentSelection == OPTION_FIRST) {
//Load the content of FIRST segment action
}
else {
//Load the content of SECOND segment action
}
}
Hope it works for you.

How to place an array in a table

Hello friends i have the problem, as parse an array and I want to put in a table,
the table is not filled with this information that brings me my array.
I could help solve this, the code used is as follows.
BuscaViewController.m
-(void) searchBarSearchButtonClicked:(UISearchBar *)search{
NSInteger success = 0;
#try {
if([[self.search text] isEqualToString:#""]) {
[self alertStatus:#"No has ingresado ningun cambio" :#"" :0];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"&criterio=%#",[self.search text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://tacomander.com.mx/php/BuscarTaquerias.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"success"] integerValue];
NSLog(#"Success: %ld",(long)success);
if(success == 1)
{
NSLog(#"Si esta bien");
[self firParsear:urlData];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"No se encontraron taquerias " :0];
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Fallo la conexion" :#"" :0];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Busqueda Fallida." :#"Error!" :0];
}
}
console if I return a query, as I put these data in the table.
- (void)firstParse:(NSData *)urlData
{
NSError *error = nil;
NSDictionary *jsoDictionar = [NSJSONSerialization JSONObjectWithData:urlData
options:kNilOptions
error:&error];
// si hubo algún error en el parseo lo mostramos
if (error != nil)
{
NSLog(#"ERROR: %#", [error localizedDescription]);
}
else {
self.taquerias = [jsonDictionar objectForKey:#"Taquerias"];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section{
return [self.taquerias count];
}
- (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];
}
NSDictionary *taquero = [self.taquerias objectAtIndex:indexPath.row];
cell.textLabel.text = [taquero objectForKey:#"nombre"];
NSString *subtitle = [NSString stringWithFormat:#"Precio: %# ",
[taquero objectForKey:#"idPrecio"]];
cell.detailTextLabel.text = subtitle;
return cell;
}
Thank you for your time and help
I think the problem is here
- (void)firstParse:(NSData *)urlData {
NSError *error = nil;
NSDictionary *jsoDictionar = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
// si hubo algún error en el parseo lo mostramos (parce trate de usar todo en ingles o lo llenan de negativos).
if (error != nil)
{
NSLog(#"ERROR: %#", [error localizedDescription]);
}
else {
self.taquerias = [jsonDictionar objectForKey:#"Taquerias"];
[yourtableview reloadData]; ---> here Code.
}
}

JSON data show on first cell

I am Developing An IOS App.On Button Click Show JSON Data In Tableview..But The Data Show ON Only First Cell Not On Other Cells..I Can Check The Data Through NSLog That Are Correct..But In Tableview Show In First Cells And Some Time App Crash And Error Data Parameters Are Nil..Warning Show on This Line
`"Incompatible Pointer Assigning To 'NSDictionary'
To
NSArray "[str = [BBServerJson sendPostRequest:json toUrl:url];]`
Any Help Or Advice Is Greatly Appreciated. Thanks In Advance.
//Button Click
BBAuthorViewController *BBAuthor =[[UIStoryboard storyboardWithName:#"Main" bundle:nil]instantiateViewControllerWithIdentifier:#"BBAuthor"];
BBAuthor.authorDetail=_adDetailsObj.authorDetail;
[self.navigationController pushViewController:BBAuthor animated:YES];
//Json
+(NSDictionary *)sendPostRequest:(NSDictionary *)params toUrl:(NSString *)urlString
{
NSMutableString *paramString =
[NSMutableString stringWithString:#""];
NSArray *keys = [params allKeys];
for (NSString *key in keys) {
[paramString appendFormat:#"%#=%#&",key,
[params valueForKey:key]];
}
NSString *postString = #"";
if ([paramString length] > 0)
postString = [paramString substringToIndex:
[paramString length]-1];
NSMutableURLRequest *request =[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *res;
NSError *error;
NSData *resp = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res error:
&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)res;
int statusCode;
statusCode = [httpResponse statusCode];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:resp options:NSJSONReadingMutableContainers error:&error];
return jsonArray;
}
NSString *url = #"https://boatbrat.com/wp-app-handler-boatsales.php";
NSMutableDictionary *json = [[NSMutableDictionary alloc]init];
[json setObject:#"AuthorListing" forKey:#"method"];
[json setObject:_authorDetail forKey:#"author"];
str = [BBServerJson sendPostRequest:json toUrl:url];
//Tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return str.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *array = [str objectForKey:#"results"];
NSDictionary *dic= [array objectAtIndex:indexPath.row];
cell.textLabel.text = [dic objectForKey:#"author_name"];
return cell;
}
I think you are returning wrong row count in numberOfRowsInSection: method.
Change the return statement to,
return [[str objectForKey:#"results"] count];

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];

Image Caching not working?

Hello everyone i’m new to ios development , i’m doing JSON parsing and fetch the data and showing on the UITableView with ImageView and Title, Everything works great but image Cacheing is a problem in my code my images are loading but it takes so much time and when i scroll my tableview it again fetch the required image for the cell. Can anybody please come up with caching solution in my present code i already googled many times but unable to figure out this. It really helpful if anyone please suggest me the similar example or assist me on this. Thanks In Advance.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *post =[[NSString alloc]init];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.xyz.com/consumer_id=1”];
NSData *postData = [ post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
data = [jsonData objectForKey:#"data"];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *myNames = [data objectAtIndex:[indexPath row]];
NSLog(#"%#",myNames);
[cell.nameLabel setText:[myNames objectForKey:#"name"]];
NSString *imageURL = [myNames objectForKey:#"image"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *imageIcon = [UIImage imageNamed:#"license.png"];
NSLog(#"ImageIcon %#",imageIcon);
[cell.thumbnailImageView setImage:imageIcon];
cell.thumbnailImageView.image = [UIImage imageWithData:imageData];
return cell;
}
Try to Show the image asynchronously in with setting placeholder image as your images are coming from web service.
dispatch_async(dispatch_get_main_queue(),^{
[image setImageWithURL:your url placeholderImage:[UIImage imageNamed:#""]];
});
Try this SDWebImage from here.
-(void)viewDidAppear:(BOOL)animated
{
NSMutableArray *arrtInvitationList=[[NSMutableArray alloc]init];
NSString * urlString=[NSString stringWithFormat:#"Your Url"];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
// NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *error1;
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
// you are getting dictinary here according ur dictinary parse the data .......
if ([[res valueForKey:#"status"]isEqualToString:#"true"]) {
NSLog(#"%d",[[res valueForKey:#"result"] count]);
for (int i=0; i<[[res valueForKey:#"result"] count]; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
//[dict setObject:[[[[res valueForKey:#"player1"] objectAtIndex:i] valueForKey:#"result"] objectAtIndex:i] ];
[arrtInvitationList addObject:dict];
[tblInvite reloadData];
}
[HUD hide:YES];
}else
{
[HUD hide:YES];
}
}];
}
//After that add this array your table view there also when u adding image add asynchronous method
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
UIImage *imagemain=[UIImage imageWithData:data];
CGSize size=imagemain.size;
UIImage *compimage=[self resizeImage:imagemain resizeSize:CGSizeMake(45,45)];
//
Cell.imgProfile.image=compimage;
// // CGSize size1=compimage.size;
// }];
this adding image to cell and resize the image also........
-(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
CGFloat actualHeight = orginalImage.size.height;
CGFloat actualWidth = orginalImage.size.width;
// if(actualWidth <= size.width && actualHeight<=size.height)
// {
// return orginalImage;
// }
float oldRatio = actualWidth/actualHeight;
float newRatio = size.width/size.height;
if(oldRatio < newRatio)
{
oldRatio = size.height/actualHeight;
actualWidth = oldRatio * actualWidth;
actualHeight = size.height;
}
else
{
oldRatio = size.width/actualWidth;
actualHeight = oldRatio * actualHeight;
actualWidth = size.width;
}
CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
UIGraphicsBeginImageContext(rect.size);
[orginalImage drawInRect:rect];
orginalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return orginalImage;
}

Resources