enter image description here .Im new to IOS. I am making an app where I want to get data from there in UITableView.
I have seen many blogs and post related to getting data in custom style, but I don't get my answer. I want to show an image in UIImageView and some labels values in label from service. Im using built in service to get data.
There are many post related to static data loading on custom. Can anyone guide how can I load data in my own custom style UItable VIEW FROM SERVICE?
Somewhat I can understand your question.My answer is here
FindHomeViewController.m
#import "FindHomeViewController.h"
#import "DataTableViewController.h"
#interface FindHomeViewController ()
#end
#implementation FindHomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)Search:(id)sender {
//Getting response from server
NSDictionary *parameters = #{
#"country": #"UAE",
#"city": #"Dubai",
#"propertytype": #"Office",
#"propertystatus": #"Available",
#"propertyarea" : #"Kanal",
#"minprice" : #"800",
#"maxprice" : #"900"
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.pk.house/app_webservices/get_properties.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil)
{
NSError *parseError = nil;
//If the response is in dictionary format
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSArray *arr=[dictionary valueForKey:#"property_data"];
NSLog(#"arr:%#",arr);
//Updating UIMain Thread
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
DataTableViewController *vc = [sb instantiateViewControllerWithIdentifier:#"DataTableViewController"];
vc.arrResprev = [arr mutableCopy];
[self.navigationController pushViewController:vc animated:YES];
});
}
else
NSLog(#"Data returned the parameter is nil here");
}];
[dataTask resume];
}
See my Custom Cell Image View
CustomeCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell
#property (nonatomic,strong) IBOutlet UILabel *nameLabel;
#property (nonatomic,strong) IBOutlet UILabel *priceLabel;
#property (nonatomic,strong) IBOutlet UILabel *locationLabel;
#property (nonatomic,strong) IBOutlet UIImageView *imgvwRes;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
DataTableViewController.h
#import <UIKit/UIKit.h>
#interface DataTableViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *tvCustomers;
#property (strong, nonatomic) NSMutableArray *listOfCustomers;
#property (strong, nonatomic) NSMutableArray *arrResprev;
#end
DataTableViewController.m
#import "DataTableViewController.h"
#import "CustomCell.h"
#interface DataTableViewController ()
#end
#implementation DataTableViewController
#synthesize tvCustomers,arrResprev,listOfCustomers;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
listOfCustomers = [[NSMutableArray alloc]init];
listOfCustomers = arrResprev;
[tvCustomers reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return listOfCustomers.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 134;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tvCustomers dequeueReusableCellWithIdentifier:#"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
if(cell == nil){
cell = nib[0];
}
cell.nameLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"dealer_name"]];
cell.priceLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"price"]];
cell.locationLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"location"]];
NSString *strImgURL = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"images"]];
NSError* error = nil;
NSURL *fileURL = [NSURL fileURLWithPath:strImgURL];
NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
UIImage *img = [[UIImage alloc] initWithData:data];
cell.imgvwRes.image = omg;
return cell;
}
For this you need to follow both Appcoda and mikesknowledgebase tutorials .
One shows how to customize UITableViewCell and other shows how to populate UITableView with data fetched from server. You will have to do it in steps.
First, design the Custom UITableViewCell.
Then, follow Mike's tutorial to learn how to set data on cell from API call.
You will use NSURLSession to make API calls.
Follow Link to learn how to make an API call.
Go through these links.
We can only help you in debugging where little amount of code will work. But cannot post code for the complete functionality.
Hope these links will help you.
Related
When i parsing json with tableview everything good when have json items but if not load json items and when i clicked back button gives me this error.
erminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
I think json don't load when i clicked fastly back button and gives this error my table view codes under.
#interface MasterViewController ()
#property (nonatomic, assign) NSInteger currentPage;
#property (nonatomic, assign) NSInteger totalPages;
#property (nonatomic, assign) NSInteger totalItems;
#property (nonatomic, assign) NSInteger maxPages;
#property (nonatomic, strong) NSMutableArray *activePhotos;
#property (strong, nonatomic) NSMutableArray *staticDataSource;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.activePhotos = [[NSMutableArray alloc] init];
self.searchResults = [[NSMutableArray alloc] init];
self.staticDataSource = [[NSMutableArray alloc] init];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.activePhotos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == [self.activePhotos count]) {
cell = [self.tableView dequeueReusableCellWithIdentifier:#"LoadingCell" forIndexPath:indexPath];
UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
[activityIndicator startAnimating];
} else {
NSDictionary *photoItem = self.activePhotos[indexPath.row];
cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [photoItem objectForKey:#"name"];
if (![[photoItem objectForKey:#"description"] isEqual:[NSNull null]]) {
cell.detailTextLabel.text = [photoItem objectForKey:#"description"];
}
}
return cell;
}
- (void)loadPhotos:(NSInteger)page
{
NSString *userismim =[[NSUserDefaults standardUserDefaults] stringForKey:#"userisim"];
NSArray* words = [userismim componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:#""];
NSLog(#"%#",nospacestring);
NSString *apiURL = [NSString stringWithFormat:#"http://bla.com/server/table.php?user=%#",nospacestring];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:apiURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *jsonError = nil;
NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",jsonObject);
[self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:#"photos"]];
self.currentPage = [[jsonObject objectForKey:#"current_page"] integerValue];
self.totalPages = [[jsonObject objectForKey:#"total_pages"] integerValue];
self.totalItems = [[jsonObject objectForKey:#"total_items"] integerValue];
self.activePhotos = self.staticDataSource;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}] resume];
}
Thanks for everything . i need your help.
You are showing activity indicator which will keep rotating till json loads.
If you are pressing back button before json loads, what happens is app tries to allocate empty reference to array which is not possible, so it throws an error.
To avoid this, you can stop userInteraction once request goes, and enable only after getting success or failure response.
To disable interaction, add
[[UIApplication sharedApplicaton] beginIgnoringInteractionEvents]
after
NSURLSession *session = [NSURLSession sharedSession];
And to enable again, add :
[[UIApplication sharedApplicaton] endIgnoringInteractionEvents]
before
if (!error) {
This will solve your issue I hope.
I am using SDWebImage to show image in UICollectionView. I am getting productImageUrl and productId as server response. Able to show the image in Custom-cell, now what I want is:
1) Display the image in large view with a UIButton(buyButton) on another UIViewController named ProductDetailViewController.(Image is showing on the ProductDetailViewController but the way i am passing image url from ProductCollectionViewController is not right I think, please review the code and suggest me some better way to do it )
2) On button click a call will be made to the server with the productId which I got earlier as Server Response.(How would I pass the dictId to ProductDetailViewController so that I can make a call to the server).
3) Getting only two key-value of an Object as response, so its ok to parse it in multiple dictionary for multiple value. But If the response contain multiple value, what will be the optimized way to parse the response.
Here is the code which i have tried.
(Sorry for long unoptimized code, still in learning phase)
ProductCollectionViewController.m
#import "ProductCollectionViewController.h"
#import "ProductCell.h"
#import "UIImageView+WebCache.h"
#import "ProductDetailViewController.h"
#interface ProductCollectionViewController ()
#property(strong, nonatomic) NSMutableArray *productList;
#end
#implementation ProductCollectionViewController
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
static NSString * const reuseIdentifier = #"Cell";
-(void)viewDidLoad
{
[super viewDidLoad];
[self getProductList];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)getProductList
{
NSURL * url = [NSURL URLWithString:#"xxxx.yyyy.zzzz"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (!error)
{
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *rsBody = responseJson[#"rsBody"];
_productList = [NSMutableArray new];
for(NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictUrl=[[NSMutableDictionary alloc]init];
NSMutableDictionary *dictProductId =[[NSMutableDictionary alloc]init];
[dictUrl setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[dictId setValue:[dict valueForKey:#"productId"] forKey:#"id"];
[_productList addObject:dictUrl];
[_productList addObject:dictId];
}
NSLog(#"urls for image: %#",_productList );
[self.collectionView reloadData];
}}];
[dataTask resume];
}
#pragma mark <UICollectionViewDataSource>
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _productList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSURL *imageUrl = [[_productList objectAtIndex:indexPath.row]valueForKey:#"url"];
[cell.productImageView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
NSString *id =[[_productList objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.productPrice.text= id;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showProduct"]) {
NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
ProductDetailViewController *destViewController = segue.destinationViewController;
NSIndexPath *indexPath = [indexPaths objectAtIndex:0]
destViewController.productName =[[_productList objectAtIndex:indexPath.row]valueForKey:#"url"];
[self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
}
#end
ProductDetailViewController.h
`#import <UIKit/UIKit.h>
#interface ProductDetailViewController : UIViewController
- (IBAction)buyButton:(id)sender;
- (IBAction)closeButton:(id)sender;
#property (weak, nonatomic) IBOutlet UIImageView *productImage;
#property (weak, nonatomic) NSString *productName;
#end`
ProductDetailViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.productImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.productName]]];
//code to get productId
}
- (IBAction)buyButton:(id)sender {
//code to make server call with productId.
}
Server Response Format in JSON
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
For your first question, this line
self.productImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.productName]]];
is blocking the main thread. Meaning the app will go to the server download the entire image before updating the screen or allowing interactions, which is bad.
NSURL *url = [[NSURL alloc]initWithString:self.productName];
dispatch_queue_t imageFetchQ = dispatch_queue_create("image fetcher", NULL);
dispatch_async(imageFetchQ, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image = [[UIImage alloc]initWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
self.productImage.image=image;
}
});
});
Try the block above instead. It will fetch the product image on a different thread.
Question two: Two transfer data between view controllers do what you're doing in prepareForSegue setup the public properties of the destination view controller.
Question three: Optimum way is to create an NSObject class that you read the data from the dictionary into properties on that class through some method called like setupFromDictionary.
Here you would have an Object called product with a productID property and productImageURL property. That way you're not constantly calling valueForKey or objectForKey on some dictionary.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am very new in IOS;
I have to post the following JSON to the server at the given link after which I will get a response.
{"req" : {"apikey" : "apikey","service" : "getcat","id" : "MOMTest00011","ptransid" : "","params" : [ {"k" : "mboxid","v" :"f7"}, {"k" : "version","v" :"0"} ]}}
Here is my link http:abcd/api
Content Type - application/json
What will be my function?How will I proceed.
Here's how one would go about setting up a NSURLRequest for POST with JSON data.
NSDictionary *dicJSON; //Represents your JSON in dictionary format.
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dicJSON options:0 error:&error];
if (error)
{
//Data was not encoded successfully.
NSLog(#"%#", [error localizedDescription]);
}
else
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"your url here"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *postLength=[NSString stringWithFormat:#"%d", [data length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
//Send this request using a NSURLConnection method here.
}
Json postMethod(singleton and header)
header
//http://smartproduct.n-school.com/
#define k_HOSPLIST #"http://"
#define k_HOSPDetails #"http://"
#endif /* Header_h */
.h file
typedef void(^completionBlock)(NSDictionary *resultDictionary,NSError
*error);
#interface .hfile : NSObject
+ (void)sendGetMethod:(NSString *)url key:(NSString *)key
withCompletionHandler:(completionBlock)handler;
+ (void)downloadDataFromServer:(NSString *)baseURL bodyData:
(NSDictionary *)body method:(NSString *)methodName postString:
(NSString*)string withCompletionHandler:(completionBlock)handler;
.m file
+ (void)sendGetMethod:(NSString *)url key:(NSString *)key
withCompletionHandler:(completionBlock)handler {
NSLog(#"url %#",url);
NSLog(#"-------> key %#",key);
NSString* encodedUrl = [url
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:encodedUrl]];
NSURLSessionTask *getMethodtask = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData * _Nullable
data,
NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"sendGetMethod - sendAsynchronousRequest - Completion
Block");
if (error)
{
//[k_AppDelegate
showAlertwithTitle:LocalizedString(#"Sorry!")
message:error.localizedDescription
buttonTitle1:LocalizedString(#"OK")
buttonTitle2:#""];
}
else if (data == nil)
{
// [k_AppDelegate showAlertwithTitle:LocalizedString(#"Error!")
message:LocalizedString(#"The specified server could not be
found.")
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
}
else
{
NSDictionary *encodeDictionary = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingMutableLeaves
error:nil];
if (![encodeDictionary isEqual:[NSNull null]] &&
encodeDictionary != nil)
{
if(handler)
{
handler(encodeDictionary, nil);
}
else if([[encodeDictionary objectForKey:#"status"]
{
//[k_AppDelegate
showAlertwithTitle:LocalizedString(#"AlertTitle") message:
[encodeDictionary objectForKey:#"message"]
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
}
}
else
{
//[k_AppDelegate
showAlertwithTitle:LocalizedString(#"Error!")
message:LocalizedString(#"The specified server could not be found.")
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
}
}
});
}];
[getMethodtask resume];
}
+ (void)downloadDataFromServer:(NSString *)baseURL bodyData:
(NSDictionary *)body method:(NSString *)methodName postString:
(NSString*)string withCompletionHandler:(completionBlock)handler;
{
NSString *getFullServer = [NSString stringWithFormat:#"%#",baseURL];
//Pass the parameters and Set the URL
NSURL *urlString = [NSURL URLWithString:getFullServer];
NSString *post = [NSString stringWithFormat:#"%#",string];
// Convert NSString to NSData format
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned
long)[postData length]];
// Create the URL Request and set the neccesary parameters
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:urlString];
[request setHTTPMethod:methodName];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData * _Nullable
data,
NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
//[(AppDelegate *)[[UIApplication
sharedApplication]delegate]stopIndicator];
if (error)
{
//[k_AppDelegate
showAlertwithTitle:LocalizedString(#"Sorry!")
message:error.localizedDescription
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
} else if (data == nil)
{
// [k_AppDelegate
showAlertwithTitle:LocalizedString(#"Error!")
message:LocalizedString(#"The specified server could not be
found.") buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
} else {
NSDictionary *encodeDictionary = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingMutableLeaves
if (![encodeDictionary isEqual:[NSNull null]] &&
encodeDictionary != nil) {
if(handler)
{
handler(encodeDictionary, nil);
}
else if ([[encodeDictionary objectForKey:#"status"]
integerValue] != 1)
{
// [k_AppDelegate
showAlertwithTitle:LocalizedString(#"AlertTitle") message:
[encodeDictionary objectForKey:#"message"]
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
}
}
else
{
//[k_AppDelegate
showAlertwithTitle:LocalizedString(#"Error!")
message:LocalizedString(#"The specified server could not be found.")
buttonTitle1:LocalizedString(#"OK") buttonTitle2:#""];
}
}
});
}];
[downloadTask resume];
}
sample coding
.h
#import <UIKit/UIKit.h>
#import "Header.h"
#interface ViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
.m
#import "ViewController.h"
#import "StringPOSTMethod.h"
#import "TableViewCell.h"
#import "HospitalViewController.h"
{
NSMutableArray *array;
NSInteger selectindex;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[StringPOSTMethod downloadDataFromServer:k_CITYLIST bodyData:nil method:#"POST" postString:[NSString stringWithFormat:#"CITY_ID=1&CITY_ID=2"] withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
{
NSLog(#"success is %#", resultDictionary);
array = [[NSMutableArray alloc]init];
array = [[resultDictionary objectForKey:#"details"] mutableCopy];
[_tableView reloadData];
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid =#"tablecell";
TableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell. cityName.text =[[array
valueForKey:#"city_name"]objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
selectindex=indexPath.row;
[self performSegueWithIdentifier:#"hospitalView" sender:self];
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"hospitalView"])
{
hospitalViewController *obj =segue.destinationViewController;
obj.cityname =[[array
valueForKey:#"city_name"]objectAtIndex:selectindex];
obj.cityId =[[array
valueForKey:#"city_id"]objectAtIndex:selectindex];
}
}
table view.h
#import <UIKit/UIKit.h>
#interface TableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *displyLbl;
#end
table view.m
#implementation TableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
hosdet.h
#import <UIKit/UIKit.h>
#import "Header.h"
#interface HospitalDetailViewController :
UIViewController<UITextViewDelegate>
#property (strong, nonatomic) IBOutlet UITextView *textview;
#property (strong,nonatomic)NSString *hospitaldetailid1;
#property (strong,nonatomic)NSString *cityiddetail1;
#end
hpde.m
#import "HospitalDetailViewController.h"
#import "StringPOSTMethod.h"
#interface HospitalDetailViewController ()
{
NSMutableArray *array;
}
#end
#implementation HospitalDetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[StringPOSTMethod downloadDataFromServer:k_HOSPITALDETAIL bodyData:nil
method:#"POST" postString:[NSString
stringWithFormat:#"CITY_ID=%#&HOSPITAL_ID=%#",
_cityiddetail1,_hospitaldetailid1] withCompletionHandler
:^(NSDictionary *resultDictionary, NSError *error)
{
NSLog(#"success is %#", resultDictionary);
array = [[NSMutableArray alloc]init];
array =[[resultDictionary objectForKey:#"details"]mutableCopy];
_textview.text = [NSString stringWithFormat:#"%#",
[array valueForKey:#"detail"]];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a
little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
hoaviewc.h
#import <UIKit/UIKit.h>
#import "Header.h"
#interface HospitalViewController :
UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *hospitalTable;
#property (strong,nonatomic)NSString *recivecity;
#property (strong,nonatomic)NSString *cityid;
#end
hosviec.m
#import "HospitalViewController.h"
#import "StringPOSTMethod.h"
#import "hospitalTableViewCell.h"
#import "depatmentViewController.h"
#interface HospitalViewController ()
{
NSMutableArray *hospitalarray;
NSInteger selecthospitalid;
}
#end
#implementation HospitalViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = self.recivecity;
[StringPOSTMethod downloadDataFromServer:k_HOSPITALLIST bodyData:nil
method:#"POST" postString:
[NSString stringWithFormat:#"CITY_ID=%#",_cityid]
withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
{
NSLog(#"success is %#", resultDictionary);
hospitalarray = [[NSMutableArray alloc]init];
hospitalarray =[[resultDictionary objectForKey:#"details"]mutableCopy];
[_hospitalTable reloadData];
}];
}
#pragma mark- UITABLE View Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(
NSInteger)section
{
return hospitalarray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid = #"hospitalcell";
hospitalTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell.hopitalList.text = [[hospitalarray
valueForKey:#"name"]objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
selecthospitalid=indexPath.row;
[self performSegueWithIdentifier:#"depatment" sender:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"depatment"]) {
depatmentViewController *obj = segue.destinationViewController;
obj.hospitalid = [[hospitalarray
valueForKey:#"hospital_id"]objectAtIndex:selecthospitalid];
obj.cityiddepartment = [NSString stringWithFormat:#"%#",_cityid];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
#end
docviec.h
#import <UIKit/UIKit.h>
#include "Header.h"
#interface DoctorsViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *doctorTable;
#property(strong,nonatomic)NSString *hospitaliddoctor;
#property(strong,nonatomic)NSString *deptiddoctor;
#end
doctviec.m
#import "DoctorsViewController.h"
#import "StringPOSTMethod.h"
#interface DoctorsViewController ()
{
NSMutableArray *doctorarray;
}
#end
#implementation DoctorsViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[StringPOSTMethod downloadDataFromServer:k_DOCTORSLIST bodyData:nil
method:#"POST" postString:
[NSString stringWithFormat:#"HOSPITAL_ID=%#&DEPARTMENT_ID=%#",
self.hospitaliddoctor,self.deptiddoctor]
withCompletionHandler:^(NSDictionary *resultDictionary, NSError *error)
{
NSLog(#"success is %#", resultDictionary);
doctorarray = [[NSMutableArray alloc]init];
doctorarray =[[resultDictionary objectForKey:#"details"]mutableCopy];
[_doctorTable reloadData];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- UITableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return doctorarray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid = #"doctr";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellid];
cell.textLabel.text = [[doctorarray
valueForKey:#"spacialist_name"]objectAtIndex:indexPath.row];
return cell;
}
depviec.h
#import <UIKit/UIKit.h>
#import "Header.h"
#interface depatmentViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *tableviewDepatment;
#property (strong,nonatomic)NSString *hospitalid;
#property (strong,nonatomic)NSString *cityiddepartment;
- (IBAction)DetailsBton:(id)sender;
#end
depvi.m
#import "depatmentViewController.h"
#import "StringPOSTMethod.h"
#import "HospitalDetailViewController.h"
#import "DoctorsViewController.h"
#interface depatmentViewController ()
{
NSMutableArray *array;
NSInteger doctorselct;
}
#end
#implementation depatmentViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[StringPOSTMethod downloadDataFromServer:k_DEPARTMENTLIST bodyData:nil
method:#"POST" postString:
[NSString stringWithFormat:#"CITY_ID=%#&HOSPITAL_ID=%#",
self.cityiddepartment,self.hospitalid] withCompletionHandler:^(NSDictionary
*resultDictionary, NSError *error)
{
NSLog(#"success is %#", resultDictionary);
array = [[NSMutableArray alloc]init];
array =[[resultDictionary objectForKey:#"details"]mutableCopy];
NSLog(#"%#",array);
[_tableviewDepatment reloadData];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark-UITable Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid=#"depatmentid";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellid];
cell.textLabel.text = [[array
valueForKey:#"dept_name"]objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
doctorselct = indexPath.row;
[self performSegueWithIdentifier:#"doctor" sender:self];
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailll"])
{
HospitalDetailViewController *obj = segue.destinationViewController;
obj.hospitaldetailid1 = self.hospitalid;
obj.cityiddetail1 = self.cityiddepartment;
}
else
{
DoctorsViewController *obj1 = segue.destinationViewController;
obj1.hospitaliddoctor = self.hospitalid;
obj1.deptiddoctor = [[array
valueForKey:#"dept_id"]objectAtIndex:doctorselct];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
- (IBAction)DetailsBton:(id)sender {
[self performSegueWithIdentifier:#"detailll" sender:self];
}
#end
I am very new at Objective C and Xcode but I am learning a little bit every day!:)
I am trying to build an application that will show a webb api in my tableview, but it does not show.. when I NSLog it, it shows that my search worked and that it got the data i was looking for but it will not show in my tableView unfortunately..
If someone as time to look at the code and try to figure out what is wrong that would be great, or if someone hade a similar problem, just throw it out there so i can check if i did the same thing:)
Best regards. Filip
(Sorry for my bad english, I`m from Sweden and in a hurry..)
- my .m file
#import "FoodTableViewController.h"
#interface FoodTableViewController ()
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
#property(nonatomic)NSMutableArray *foodNames;
#end
#implementation FoodTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.foodNames = [#[]mutableCopy];
self.searchBar.delegate = self;
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchbar
{
NSString *urlString = [NSString stringWithFormat:#"http://matapi.se/foodstuff?query=%#",self.searchBar.text];
NSURL *URL = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *parseError;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
dispatch_async(dispatch_get_main_queue(),^{
for(int i=0;i<json.count;i++){
NSString *foodName = json[i][#"name"];
[self.foodNames addObject:foodName];
NSLog(#"Added: %#",foodName);
NSLog(#"FOODLIST LENGTH: %d",self.foodNames.count);
}
});
}];
[task resume];
[self.tableView reloadData];
}
#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 self.foodNames.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
if(self.foodNames[indexPath.row]){
NSLog(#"Cell text %#",self.foodNames[indexPath.row]);
cell.textLabel.text = self.foodNames[indexPath.row];
}else{
cell.textLabel.text = #"Loading..";
}
return cell;
}
#end
- my .h file
#import <UIKit/UIKit.h>
#interface FoodTableViewController : UITableViewController<UISearchBarDelegate>
#end
dataTaskWithRequest:... is an asynchronous method, which means that the results are not available at the time of your reloadData call. You'll need to add that call after all your data is added to the array. In part...
for(int i=0;i<json.count;i++){
NSString *foodName = json[i][#"name"];
[self.foodNames addObject:foodName];
NSLog(#"Added: %#",foodName);
NSLog(#"FOODLIST LENGTH: %d",self.foodNames.count);
}
[self.tableView reloadData];
hi I'm trying to view the image and description form tableview to detailviewcontroller but not I'm not able get it. I'm fetching the image form server i have stored the image url and using the json and php coding I'm getting the image url using the NSURLConnectionDelegate viewing the images and description in tableview .
i have trying many ways to view those images in the tableview but getting the images.
detailview controller.h file coding
#import <UIKit/UIKit.h>
#import "image.h"
#class image;
#interface viewdetailpoliticalViewController : UIViewController<NSURLConnectionDelegate>
{
NSURLConnection *connection;
}
#property (strong,nonatomic) NSString *value;
#property (strong,nonatomic) UIImage *imm;
#property (strong, nonatomic) IBOutlet UIImageView *imageview;
#property (strong, nonatomic) IBOutlet UILabel *dcp
#property (strong, nonatomic) NSMutableData *responseData;
-(void)setDataSource:(image *)inImageOb;
#end
this is my detailview controller.m file coding
#import "viewdetailpoliticalViewController.h"
#import "image.h"
#interface viewdetailpoliticalViewController ()
#end
#implementation viewdetailpoliticalViewController
#synthesize imageview,dcp;
#synthesize value,imm;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageview.image = self.imm;
self.dcp.text = self.value;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setDataSource:(image *)inImageOb
{
self.value = inImageOb.desp;
NSURL *url = [NSURL URLWithString:inImageOb.img];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
{
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
UIImage *image = [UIImage imageWithData:self.responseData];
self.imm = image;
}
#end
this is my tableview controller m file coding:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"Detailsegue" sender:indexPath];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"Detailsegue"]) {
viewdetailpoliticalViewController *detailvc = (viewdetailpoliticalViewController *)segue.destinationViewController;
NSIndexPath *indexPath =[self.mytableview indexPathForSelectedRow];
[detailvc setDataSource:[imgevery objectAtIndex:indexPath.row]];
}
}
this is code i have used to fetch the datas using json
-(void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
imgevery =[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
NSString * dd = [[json objectAtIndex:i]objectForKey:#"imgp"];
NSString * plae =[[json objectAtIndex:i]objectForKey:#"disp"];
image *myimg =[[image alloc]initWithimg:dd anddesp:plae];
[imgevery addObject:myimg];
}
[self.mytableview reloadData];
}
this is the code i have used for the tableview cell
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return imgevery.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier =#"Cell";
imgpoliticalCell *cell =(imgpoliticalCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell== nil) {
cell = [[imgpoliticalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
[cell setDataSource:[imgevery objectAtIndex:indexPath.row]];
// cell.thumbImageView.image = _img;
return cell;
}
Found the problem the problem is u passing data through Setimage Source
you set image in viewDidload itself after -(void)setDataSource:(image *)inImageOb only viewDidload () will run but you assigned image to imageview in viewDidLoad() itself
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageview.image = self.imm;
self.dcp.text = self.value;
// Do any additional setup after loading the view.
}
(void)connectionDidFinishLoading will run after ViewDidLoad()
SO you ve to set Image in - (void)connectionDidFinishLoading:(NSURLConnection *)connection; only which will run at last when connection didFinish so do like this
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
imm = [UIImage imageWithData:self.responseData];
self.dcp.text = value;
self.imageview.image = imm;
}
Hope Now works...