detailtableview controller to push the image from tableview - ios

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

Related

Table View Cell - UITableView - Cannot show multiple rows in detailed view

I am using Tableview to display Name from recipes Array which works great and displays all name in table view from recipes Array. When i tap on one of the recipe it displays the name on detailed view.
What i am stuck of is, how to display other fields in the detailed view.I have an Array ( array name: ingredients ) which has contents of that specific recipe, example ingredients.
I tried with
cell.textLabel.text = [ingredients objectAtIndex:indexPath.row];
RecipeDetailViewController.h
#import <UIKit/UIKit.h>
#interface RecipeDetailViewController : UIViewController
#property (nonatomic, strong) IBOutlet UILabel *recipeLabel;
#property (nonatomic, strong) NSString *recipeName;
#property (strong, nonatomic) IBOutlet UILabel *recipeCountry;
#property (nonatomic, strong) NSString *recipeCountryName;
#end
but it doesn't show anything in RecipeBookViewController.m
Here is my Original code
#import "RecipeBookViewController.h"
#import "RecipeDetailViewController.h"
#interface RecipeBookViewController ()
#end
#implementation RecipeBookViewController {
NSArray *recipes;
}
#synthesize tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *allCourseData=[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]];
NSError *error;
NSMutableDictionary *JsonObject = [NSJSONSerialization
JSONObjectWithData:allCourseData options:NSJSONReadingMutableContainers
error:&error];
NSArray *loans = JsonObject[#"loans"];
// Create a new loans array for store the new items
NSMutableArray *newLoans = [NSMutableArray array];
NSMutableArray *arrCountry = [NSMutableArray array];
for (NSDictionary *loan in loans) {
NSNumber *ident = loan[#"id"];
NSString *name = loan[#"name"];
NSDictionary *description = loan[#"description"];
NSDictionary *location = loan[#"location"];
NSString *country = location[#"country"];
NSString *status = loan[#"status"];
NSDictionary *geo = location[#"geo"];
NSString *geoprint = geo[#"pairs"];
[newLoans addObject:name];
[arrCountry addObject:country];
}
recipes=newLoans;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [recipes count];
}
//Display Name in Detail View
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"RecipeCell";
//Displays name
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showRecipeDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
RecipeDetailViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
}
}
#end
RecipeDetailViewController.m
#import "RecipeDetailViewController.h"
#interface RecipeDetailViewController ()
#end
#implementation RecipeDetailViewController
#synthesize recipeLabel;
#synthesize recipeName;
#synthesize recipeCountry;
#synthesize recipeCountryName;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the Label text with the selected recipe
recipeLabel.text = recipeName;
recipeCountry.text=recipeCountryName;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Here are the screenshots of both Views
Changes in your loop;
for (NSDictionary *loan in loans) {
NSNumber *ident = loan[#"id"];
NSString *name = loan[#"name"];
NSDictionary *description = loan[#"description"];
NSDictionary *location = loan[#"location"];
NSString *country = location[#"country"];
NSString *status = loan[#"status"];
NSDictionary *geo = location[#"geo"];
NSString *geoprint = geo[#"pairs"];
[newLoans addObject:#[
#"name":name,
#"description":description,
#"country ":country
]]; // Same way add all keys
//Or
/*
NSMutableDictionary* dicData = [NSMutableDictionary dictionary];
newLoans[#"name"] = name;
newLoans[#"description"] = description;
newLoans[#"country"] = country;
[newLoans addObject:dicData];
*/
}
recipes=newLoans;
Change when retrieving;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
. . .
NSDictionary * dict = [recipes objectAtIndex:indexPath.row];
cell.textLabel.text = dict[#"name"];
return cell;
}
Same way pass the complete dictionary to the RecipeDetailViewController and show other information there.

Send Json Request By POST method [closed]

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

ViewController not properly sending over NSURL data to Destination ViewController

When a user taps a cell, I want itemURL to be set to that cells "Item URL" property. Once it does this, it should then send over the itemURL in prepareForSegue over to WebViewController, as I've attempted to do. When I have WebViewController NSLog the itemURL property however, it comes up as null. How can I make sure the value is sent over properly?
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#import "WebViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#property (strong, nonatomic) NSString *searchTerm;
#property (strong, nonatomic) NSURL *itemURL;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
_matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _matchCenterArray.count;
}
//the part where i setup sections and the deleting of said sections
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 21.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
headerView.backgroundColor = [UIColor lightGrayColor];
_searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
headerLabel.text = [NSString stringWithFormat:#"%#", _searchTerm];
headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor lightGrayColor];
[headerView addSubview:headerLabel];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.tag = section;
deleteButton.frame = CGRectMake(300, 2, 17, 17);
[deleteButton setImage:[UIImage imageNamed:#"xbutton.png"] forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:deleteButton];
return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 65;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
// NSLog(#"The url is: '%#'", itemURL);
[self performSegueWithIdentifier:#"WebViewSegue" sender:self];
}
- (void)deleteButtonPressed:(id)sender
{
// links button
UIButton *deleteButton = (UIButton *)sender;
// Define the sections title
NSString *sectionName = _searchTerm = [[[[_matchCenterArray objectAtIndex:deleteButton.tag] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
// Run delete function with respective section header as parameter
[PFCloud callFunctionInBackground:#"deleteFromMatchCenter"
withParameters:
#{#"searchTerm": sectionName,}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
WebViewController *controller = (WebViewController *) segue.destinationViewController;
controller.itemURL = self.itemURL;
}
#end
WebViewController.h:
#import <UIKit/UIKit.h>
#import "MatchCenterViewController.h"
#interface WebViewController : UIViewController <UIWebViewDelegate>
#property (strong, nonatomic) NSURL *itemURL;
#property (weak, nonatomic) IBOutlet UIWebView *myWebView;
#end
WebViewController.m:
#import "WebViewController.h"
#interface WebViewController ()
#end
#implementation WebViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"The url is: '%#'", _itemURL);
// _myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
// _myWebView.delegate=self;
// [self.view addSubview:_myWebView];
self.myWebView.delegate = self;
//////////
NSURLRequest *request = [NSURLRequest requestWithURL:_itemURL];
//4
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//5
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil) [self.myWebView loadRequest:request];
else if (error != nil) NSLog(#"Error: %#", error);
}];
[self.myWebView setScalesPageToFit:YES];
//////
//[self.myWebView loadRequest:request];
}
- (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
In your didSelectRowForIndexPath: instead of
NSURL *itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
use
self.itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];

website not loading in UIWebView

I've set my code up so that when a user taps a cell in the UITableView, it segues to WebViewController, and passes that cells "Item URL" property along the way. In the WebViewController class, I initialize a UIWebView, and have it load the respective URL. For some reason, it shows up blank and doesn't do any loading. How can I set my WebViewController to begin loading the webpage once it segues over?
WebViewController.h:
#import <UIKit/UIKit.h>
#import "MatchCenterViewController.h"
#interface WebViewController : UIViewController <UIWebViewDelegate>
#property (strong, nonatomic) NSURL *itemURL;
#property (strong, nonatomic) IBOutlet UIWebView *myWebView;
#end
WebViewController.m:
#import "WebViewController.h"
#interface WebViewController ()
#end
#implementation WebViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
_myWebView.delegate=self;
[self.view addSubview:_myWebView];
self.myWebView.delegate = self; //set the delegate first before calling LoadRequest
NSURL *url = [NSURL URLWithString:_itemURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView setScalesPageToFit:YES];
[self.myWebView loadRequest:request];
}
- (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
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#import "WebViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
//irrelevant code hidden for conciseness
#property (strong, nonatomic) NSArray *matchCenterArray;
#property (strong, nonatomic) NSString *searchTerm;
#property (strong, nonatomic) NSURL *itemURL;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
_matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _matchCenterArray.count;
}
//the part where i setup sections and the deleting of said sections
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 21.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//irrelevant code removed for conciseness
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//irrelevant code removed for conciseness
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 65;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
[self performSegueWithIdentifier:#"WebViewSegue" sender:self];
}
- (void)deleteButtonPressed:(id)sender
{
// links button
UIButton *deleteButton = (UIButton *)sender;
// Define the sections title
NSString *sectionName = _searchTerm = [[[[_matchCenterArray objectAtIndex:deleteButton.tag] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
// Run delete function with respective section header as parameter
[PFCloud callFunctionInBackground:#"deleteFromMatchCenter"
withParameters:
#{#"searchTerm": sectionName,}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
WebViewController *controller = (WebViewController *) segue.destinationViewController;
controller.itemURL = self.itemURL;
}
#end
This line in your code indicates that you have a WebView in your Xib file and you have an outlet attached to it:
#property (strong, nonatomic) IBOutlet UIWebView *myWebView;
So When you already have a webView defined in your Xib file, why are you creating another UIWebView and assigning it to the IBOutlet's webView? There is no point in allocating a new webView and adding it as subview. That is, you should discard these lines:
_myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
_myWebView.delegate=self;
[self.view addSubview:_myWebView];
The reason is that when you already have a WebView in Xib file then you don't need another instance of it. Simply do:
self.myWebView.delegate = self;
NSURL *url = [NSURL URLWithString: itemURL]; //itemURL must be a NSString. If it is a NSURL, then you should skip this line and put itemURL in the next line instead of "url"
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView setScalesPageToFit:YES];
[self.myWebView loadRequest:request];
There's a bug in your code:
NSURL *url = [NSURL URLWithString:_itemURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
_itemURL is an NSURL object, not a NSString. You should just be able to do
NSURLRequest *request = [NSURLRequest requestWithURL:_itemURL];
provided _itemURL is set.
In the viewDidLoad method of your WebViewController, add this code:
-(void)viewDidLoad {
[super viewDidLoad];
UIWebView* webView = [UIWebView alloc] initWithFrame:self.view.frame];
[self.view addSubView:webView];
NSURLRequest* request = [NSURLRequest requestWithURL:self.itemURL; cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];
[webView loadRequest:request];
}

Fetching Image from Parse class

Beginner here guys. I already managed to get the text from Parse class to table view. In the same class i have another column where I put the associated image file and somehow i could not get the image file. I will be glad if you can help me with this issue. Parse class name is News and the column i would like to get is imageFile. Here is my code.
.h file
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "TableCell.h"
#interface ViewController : UIViewController <UITableViewDelegate> {
NSArray *events;
}
#property (weak, nonatomic) IBOutlet UITableView *newsTable;
#end
.m file
#import "ViewController.h"
#import "TableCell.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize newsTable;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self performSelector: #selector(retreiveFromParse)];
}
- (void) retreiveFromParse {
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"News"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
events = [[NSArray alloc] initWithArray:objects];
}
[newsTable reloadData];
}];
}
//*********************Setup table of folder names ************************
//get number of sections in tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
//get number of rows by counting number of folders
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return events.count;
}
//setup cells in tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//setup cell
static NSString *CellIdentifier = #"EventCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
PFObject *tempObject = [events objectAtIndex:indexPath.row];
cell.TitleLabel.text = [tempObject objectForKey:#"Event"];
return cell;
}
//user selects folder to add tag to
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cell tapped");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
My Cell.h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface TableCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *TitleLabel;
#end
My cell.m
#import "TableCell.h"
#implementation TableCell
#synthesize TitleLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Just after
PFObject *tempObject = [events objectAtIndex:indexPath.row];
cell.TitleLabel.text = [tempObject objectForKey:#"Event"];
Write below lines..
PFFile *imageFile = [tempObject objectForKey:#"image"];
PFImageView *imageView = [[PFImageView alloc] init];
imageView.file = imageFile;
[imageView loadInBackground:^(UIImage *img,NSError *error){
if(!error)
{
UIImageView *yourImageView = [[UIImageView alloc] init];
yourImageView.image = imageView.image;
/*OR*/
cell.imageView.image = imageView.image;
}
}];
This might get you going.
This will fetch the associated file and put it in cell.imageView, which is a PFImageView (the Parse edition of UIImageView):
PFObject *tempObject = [events objectAtIndex:indexPath.row];
cell.TitleLabel.text = [tempObject objectForKey:#"Event"];
PFFile *imageFile = [tempObject objectForKey:#"imageFile"];
if (imageFile) {
cell.imageView.file = imageFile;
[cell.imageView loadInBackground];
} else {
cell.imageView.image = [UIImage imageNamed:#"AvatarPlaceholder.png"];
}

Resources