I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
#import "thirdViewController.h"
#import "ViewController.h"
#import "DetailViewController.h"
#import "secondViewController.h"
#interface thirdViewController (){
NSDictionary *currencies;
NSMutableArray *arrayCurrenciesKeys;
NSMutableData *webData;
NSURLConnection *connection ;
NSMutableArray *array;
NSMutableArray *temp;
}
#end
#implementation thirdViewController
#synthesize tableView,cityname;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"Типи валют";
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
array=[[NSMutableArray alloc]init];
NSURL *url =[NSURL URLWithString:#"http:resources.finance.ua/ua/public/currency-cash.json"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
connection= [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData alloc] init];
}
tableView.backgroundColor=[UIColor clearColor];
tableView.alpha=0.9;
}
-(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 *CellIdentifier =#"Cell"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error");
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed =[allDataDictionary objectForKey:#"organizations";
for(NSDictionary *diction1 in feed){
NSString *label1 = [diction1 objectForKey:#"cityId"];
[temp addObject:label1];
NSString *label2 =[[allDataDictionary objectForKey: #"cities" ] objectForKey:[NSString stringWithFormat:#"%#",label1]];
if(![array containsObject:label2]){
[array addObject:label2];}
else{
;
}
[[self tableView]reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"Banks" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"Banks"]) {
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Also i add segue identificator in the storyboard. I also try to present it with navigation controller,but it doesn't work too.
I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
I assume that your "first" is ViewController.h
1- Are you sure that the identifier of the segue from thirdViewController to secondViewController is #"Banks"?
You can be misleading it with the identifier of the segue from ViewController to thirdViewController.
2- Double check that you have the exact same string in Interface Builder and in code.
It can be #"Bankss" in Interface Builder and can be #"Banks" in code.
Related
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
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...
I think I have a pretty easy task, but somehow it doesn't want to work. I am a total beginner in objective-c, so I guess it's just a small mistake. I still don't really know what I do, currently it's more like copy&paste programming. Like I don't really know if I need the IBOutlet in the interface or as a property or as both.
What I have:
A ViewController with a Button, a Label and a Table View. The button connects to a sharepoints server and reads a list and adds the value to an array. This part works.
Delegate and DataSource outlet is connected to the View Controller.
What I want:
The array should be the datasource of the Table View, so I just want it to refresh after I've read the new data in the array. The test data I add in the viewDidLoad function to the array, shows up. So I guess I somehow connected the array to the table view.
I'll give you the full code:
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UILabel *output;
IBOutlet UITableView *tableView;
NSMutableData *webData;
NSString *finaldata;
NSString *convertToStringData;
NSMutableString *nodeContent;
}
#property (nonatomic, retain) UILabel *output;
#property (nonatomic, weak) IBOutlet UITableView *tableView;
-(IBAction)invokeService:(UIButton *) sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *foundUrlaub;
}
#end
#implementation ViewController
#synthesize output;
- (void)viewDidLoad
{
[super viewDidLoad];
// SOME TEST DATA... THIS SHOWS UP IN MY TABLE VIEW
foundUrlaub = [[NSMutableArray alloc]init];
[foundUrlaub addObject:#"first cell"];
[foundUrlaub addObject:#"second cell"];
[foundUrlaub addObject:#"third cell"];
}
-(IBAction)invokeService:(UIButton *) sender
{
// connection to sharepoint
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"didReceiveData");
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with the Connection");
NSLog(error.description);
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
NSLog(#"canAuthenticateAgainstProtectionSpace");
return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"didReceiveAuthenticationChallenge");
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"XXXXXX" password:#"XXXXXX" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
convertToStringData = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?<=ows_Title=')(.*)(?=' ows_MetaInfo)" options:0 error:NULL];
NSArray *matches = [regex matchesInString:convertToStringData options:0 range:NSMakeRange(0, [convertToStringData length])];
// HERE I LOAD SOME DATA IN THE ARRAY
[foundUrlaub removeAllObjects];
for (NSTextCheckingResult *match in matches)
{
NSRange matchRange = [match rangeAtIndex:1];
NSString *matchString = [convertToStringData substringWithRange:matchRange];
NSLog(#"Match: %#", matchString);
[foundUrlaub addObject:matchString]; // <- ADDS 3 STRINGS TO ARRAY
}
// THIS DOES NOT WORK!
[tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [foundUrlaub count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [foundUrlaub objectAtIndex:indexPath.row];
return cell;
}
#end
try using [_tableView reloadData]; You didn't #synthesize your tableView in your .m so you have to use the autosynthesized identifier
Your code looks fine ,
make sure
IBOutlet for tableView is connected properly
Datasource and delegates from nib is connected to the files owner
A must watch and a must read for you
You have to connect the Outlet in the Interfacebuilder to your UITableview tableView.
You are trying to reload table from separate thread. so UIView can be changed only from main thread so do something like this:
[tableView performSelectorOnMainThread:#selector(reloadData)
withObject:nil
waitUntilDone:YES];
Can anyone point me in the right direction of a good tutorial or possibly answer this question.
I have some JSON to be returned on my web server
{
first_name: "Joe";
last_name: "Smith";
department: "Human Resources";
}
How do I make a http request to get this information at the click of a button and display as text on the iphone.?
Complete newbie so please 'dumb' down.
create a jsonviewcontroller class
#import <UIKit/UIKit.h>
#interface JSONViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
NSString *label;
}
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
- (IBAction)getTop10AlbumAction:(id)sender;
#end
then in implementation class:-
#import "JSONViewController.h"
#interface JSONViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSString *category;
}
#end
#implementation JSONViewController
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Failed with Error");
}
this is the place where actual parsing happens, we fetch the title of albums from respective dictionary and arrays. to understand this first go to this link http://jsonviewer.stack.hu/#http://itunes.apple.com/us/rss/topalbums/limit=10/json this is the json viewer which shows the structure of the content that we are going to access. dont panic! its really easy if u try parsing some json urls
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry=[feed objectForKey:#"entry"];
for (NSDictionary *dict in arrayOfEntry) {
NSDictionary *title=[dict objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self myTableView]reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(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 *CellIdentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//clear background color
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
//set cell text
cell.textLabel.text=[array objectAtIndex:indexPath.row];
//set cell accessory type
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
here we specify the itunes url that we are going to parse and make connection request
- (IBAction)getTop10AlbumAction:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://itunes.apple.com/us/rss/topalbums/limit=10/json"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
[[self myTableView]reloadData];
}
#end
i hope i have made it clear enough!
I suggest you two different tutorials:
Creating a simple interface. Here is a sample from Apple that have a button and a text displayed: iOS Button - Label sample
Insert into controller code (i.e. changeGreeting:) the code that calls the webservice: iOS JSON Webservice tutorial
I'm trying JSON parser for first time and i need a little help
When I try to populate a table view it works OK, but when I scroll the table or select a row the app crashes. I would appreciate any help.
Here are the files I have:
#import <UIKit/UIKit.h>
#class RootViewController;
#interface BooksJsonAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
NSMutableArray *statuses;
NSMutableData *responseData;
}
#property(nonatomic, retain)NSMutableArray *statuses;
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#end
and
#import "BooksJsonAppDelegate.h"
#import "RootViewController.h"
#import "SBJson.h"
#implementation BooksJsonAppDelegate
#synthesize window;
#synthesize navigationController,statuses;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://assignment.golgek.mobi/api/v10/items"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
statuses = [parser objectWithString:json_string error:nil];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection Failed: %#",[error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
}
- (void)dealloc {
[navigationController release];
[window release];
[super dealloc];
}
#end
then the root view controller
#import <UIKit/UIKit.h>
#class DetailView,BooksJsonAppDelegate;
#interface RootViewController : UITableViewController {
DetailView *detailView;
BooksJsonAppDelegate *booksAppDelegate;
}
#end
and
#import "RootViewController.h"
#import "DetailView.h"
#import "BooksJsonAppDelegate.h"
#implementation RootViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
booksAppDelegate = (BooksJsonAppDelegate *)[[UIApplication sharedApplication] delegate];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [booksAppDelegate.statuses count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
NSDictionary *aBook = [booksAppDelegate.statuses objectAtIndex:[indexPath row]];
cell.textLabel.text = [aBook objectForKey:#"title"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.textLabel.minimumFontSize = 10;
cell.textLabel.numberOfLines = 4;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *aBook = [booksAppDelegate.statuses objectAtIndex:[indexPath row]];
detailView = [[DetailView alloc] initWithNibName:#"DetailView" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailView.title = [aBook objectForKey:#"title"];
[self.navigationController pushViewController:detailView animated:YES];
[detailView release];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
You will probably need to retain your statuses
statuses = [[parser objectWithString:json_string error:nil] retain];
The JSON parser will return an autoreleased object :)
As Dan points out in the comments the better way of doing this is to set the property like this :
self.statuses = [parser objectWithString:json_string error:nil];
This has the advantage of not leaking memory if you set it twice and you can use KVO ot tell if it's changed. Much better :)
Are you sure booksAppDelegate.statuses is correctly populated?
You can check this by logging the json proces, after statuses = [parser objectWithString:json_string error:nil];
just add the following line: NSLog(#"%#",[statuses description]); to see what data is put into the dictionary