Pass string from UITableView to UIView in iOS - iphone

I want to pass 2 string selected from UITableview (CompleteView) to new UIView (DetailView)
This is my code:
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
When run, previewString not send to DetailView. I'm debug, when run strPreview and strMemo in DetailView is 0x00000. Thanks in advance

You can pass custom Initialisers like below . If you wish you can add one parameter
to custom Initialisers
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300) andPreviewstring:previewString];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview;

try this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[detailAlert createWebView];
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
write code for string allocation
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
//add following two lines
strPreview = [[NSString alloc] init];
strMemo = [[NSString alloc] init];
//........
return self;
}
-(void) createWebView {
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
}

The problem here is you are setting two properties in detail view after initializing DetailView. But you are trying to use a property values within the initializer which are yet to be set.
As I can see there are two options you can try out.
Write another initializer which accept these two properties. So that you can use those two properties in that initializer.
(id)initWithFrame:(CGRect)frame strMemo:(NSString *)memo strPreview:(NSString *)preview {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:preview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
Or else you can extract the logic in the current initializer and put them in to a separate method which you can called after setting two properties from the CompleteView.

Related

Exec Bad access while scrolling uitableview

I am trying to populate a list of XML data in my tableview. There is a Uiviewcontroller which holds the tableview, one xmlparser which download and parse data and a class which holds the properties of the XML data.
UIViewcontroller.h
#import <UIKit/UIKit.h>
#import "XMLParser.h"
#interface TableViewTutViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *myTableView;
XMLParser *xmlParser;
EnquiryData *currentEnquiry;
}
#property (nonatomic, retain) IBOutlet UITableView *myTableView;
#property(nonatomic, retain) XMLParser *xmlParser;
#property(nonatomic, retain) EnquiryData *currentEnquiry;
#end
UIViewcontroller.m
#import "TableViewTutViewController.h"
#import "EnquiryViewController.h"
#import "AppDelegate.h"
#implementation TableViewTutViewController
#synthesize xmlParser;
#synthesize myTableView;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)viewDidLoad
{
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *welcome= #"Welcome ";
welcome= [welcome stringByAppendingString:app.firstname];
NSString *url = #"http://demos4clients.com/iphone/csi/register.php?choice=getEnquiryList&id_user=";
url = [url stringByAppendingString:app.id_user];
xmlParser = [[XMLParser alloc] loadXMLByURL:url];
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0 || section == 1)
return 1;
else{
NSLog(#"%i", [[self.xmlParser datas]count]);
int i = (int)[[self.xmlParser datas] count];
i++;
return i;
}
}
- (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];
cell.textLabel.highlightedTextColor = [UIColor yellowColor];
}
if(indexPath.section == 0){
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:20];
cell.textLabel.text = #"Add Enquiry";
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.selectionStyle = UITableViewCellAccessoryNone;
}
if(indexPath.section == 1)
{
if(indexPath.row == 0)
{
cell.textLabel.text = #"Enquiry";
UIImage *accept= [UIImage imageNamed:#"accept_ico.png"];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeCustom];
acceptButton.frame = CGRectMake(110, 10, 20, 21);
[acceptButton.layer setBorderWidth:0];
[acceptButton setBackgroundImage:accept forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:acceptButton];
[acceptButton release];
[accept release];
UIImage *view= [UIImage imageNamed:#"view_ico.png"];
UIButton *viewButton = [UIButton buttonWithType:UIButtonTypeCustom];
viewButton.frame = CGRectMake(190, 10, 20, 21);
[viewButton.layer setBorderWidth:0];
[viewButton setBackgroundImage:view forState:UIControlStateNormal];
[viewButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:viewButton];
[viewButton release];
[view release];
UIImage *new= [UIImage imageNamed:#"new_ico.png"];
UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
newButton.frame = CGRectMake(270, 10, 20, 21);
[newButton.layer setBorderWidth:0];
[newButton setBackgroundImage:new forState:UIControlStateNormal];
[newButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:newButton];
[new release];
[newButton release];
}
}
if(indexPath.section == 2){
currentEnquiry = [[xmlParser datas] objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:20];
cell.textLabel.text = currentEnquiry.makeCar;
[currentEnquiry release];
UILabel * acceptLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 8, 30, 30)];
acceptLabel.backgroundColor = [UIColor clearColor];
acceptLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
acceptLabel.textColor=[UIColor blueColor];
acceptLabel.numberOfLines=0;
acceptLabel.lineBreakMode=UILineBreakModeWordWrap;
acceptLabel.text = #"12";
[cell.contentView addSubview:acceptLabel];
[acceptLabel release];
UILabel * viewLabel = [[UILabel alloc] initWithFrame:CGRectMake(190, 8, 30, 30)];
viewLabel.backgroundColor = [UIColor clearColor];
viewLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
viewLabel.textColor=[UIColor blueColor];
viewLabel.numberOfLines=0;
viewLabel.lineBreakMode=UILineBreakModeWordWrap;
viewLabel.text = #"1";
[cell.contentView addSubview:viewLabel];
[viewLabel release];
UILabel * newLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 8, 30, 30)];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
newLabel.textColor=[UIColor blueColor];
newLabel.numberOfLines=0;
newLabel.lineBreakMode=UILineBreakModeWordWrap;
newLabel.text = #"5";
[cell.contentView addSubview:newLabel];
[newLabel release];
}
return cell;
}
#end
XML.h
#import <Foundation/Foundation.h>
#interface EnquiryData : NSObject
{
NSString *makeCar;
NSString *modelCar;
NSString *yearCar;
NSString *minPrice;
NSString *maxPrice;
NSString *minRun;
NSString *maxRun;
NSString *location;
NSString *fuelType;
NSString *searchRadius;
}
#property (nonatomic, retain) NSString *makeCar;
#property (nonatomic, retain) NSString *modelCar;
#property (nonatomic, retain) NSString *yearCar;
#property (nonatomic, retain) NSString *minPrice;
#property (nonatomic, retain) NSString *maxPrice;
#property (nonatomic, retain) NSString *minRun;
#property (nonatomic, retain) NSString *maxRun;
#property (nonatomic, retain) NSString *location;
#property (nonatomic, retain) NSString *fuelType;
#property (nonatomic, retain) NSString *searchRadius;
#end
XML..m file
#import "EnquiryData.h"
#implementation EnquiryData
#synthesize makeCar;
#synthesize modelCar;
#synthesize yearCar;
#synthesize minPrice;
#synthesize maxPrice;
#synthesize minRun;
#synthesize maxRun;
#synthesize searchRadius;
#synthesize location;
#synthesize fuelType;
#end
parser(.h) file
#import <Foundation/Foundation.h>
#import "EnquiryData.h"
#interface XMLParser : NSObject<NSXMLParserDelegate>
{
NSMutableString *currentNodeContent;
NSMutableArray *datas;
NSXMLParser *parser;
EnquiryData *recentEnquiry;
}
#property (readonly, retain) NSMutableArray *datas;
-(id) loadXMLByURL:(NSString *)urlString;
#end
parser.m
#import "XMLParser.h"
#implementation XMLParser
#synthesize datas;
-(id) loadXMLByURL:(NSString *)urlString
{
datas = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementname isEqualToString:#"enquiry"])
{
recentEnquiry = [EnquiryData alloc];
}
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:#"make"])
{
recentEnquiry.makeCar = currentNodeContent;
}
if ([elementname isEqualToString:#"model"])
{
recentEnquiry.modelCar = currentNodeContent;
}
if ([elementname isEqualToString:#"model_yr"])
{
recentEnquiry.yearCar = currentNodeContent;
}
if ([elementname isEqualToString:#"min_price"])
{
recentEnquiry.minPrice = currentNodeContent;
}
if ([elementname isEqualToString:#"max_price"])
{
recentEnquiry.maxPrice = currentNodeContent;
}
if ([elementname isEqualToString:#"min_run"])
{
recentEnquiry.minRun = currentNodeContent;
}
if ([elementname isEqualToString:#"max_run"])
{
recentEnquiry.maxRun = currentNodeContent;
}
if ([elementname isEqualToString:#"fuel_type"])
{
recentEnquiry.fuelType = currentNodeContent;
}
if ([elementname isEqualToString:#"location"])
{
recentEnquiry.location = currentNodeContent;
}
if ([elementname isEqualToString:#"search_radius"])
{
recentEnquiry.searchRadius = currentNodeContent;
[datas addObject:recentEnquiry];
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
You have use the release statement with out allocation
when ever you allocate the memory for object then only use for release statement for that object
For Ex: UIButton *btn = [UIButton alloc]init];
then release the end of button usage [btn release];
Once Crass check this statement [currentEnquiry release]; also
Implement this parser delegate method in your XMLParser .m file:
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadTable" object:nil];
}
Set numberOfRows integer variable to Zero in ViewController.m viewDidLoad method
-(void)viewDidLoad
{
numberOfRows = 0;
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *welcome= #"Welcome ";
welcome= [welcome stringByAppendingString:app.firstname];
NSString *url = #"http://demos4clients.com/iphone/csi/register.php?choice=getEnquiryList&id_user=";
url = [url stringByAppendingString:app.id_user];
xmlParser = [[XMLParser alloc] loadXMLByURL:url];
[super viewDidLoad];
}
Implement Observer for this notification in ViewController.m viewWillAppear method i.e.
-(void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadTable:) name:#"ReloadTable" object:nil];
}
- (void)reloadTable: (NSNotification *)notif
{
numberOfRows = [[self.xmlParser datas]count];
[table reloadData];
}
Implement remove Observer for this notification in ViewController.m viewWillDisappear method i.e.
- (void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
In UITableView datasource Method for number Of Rows In Section implement this way:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(numberOfRows == 0)
return 0;
return (section == 0 || section == 1) ? 1 : numberOfRows + 1;
}
I am sure you will not get exe bad access problem

Opening a pdf inside the app breaks the design

I'm having some kind of problems with one thing, i'm making an app and i have a webview that shows a pdf file, and i have a button if clicked will call an UIDocumentInteractionController (open the pdf in a new window).
I will leave screenshots to make it easier:
When i open the app:
http://imgur.com/dpIEd
After i open the UIDocumentInteractionController:
http://imgur.com/VYV2N
Here's the code too
.h file
#interface pdfView : UIViewController <UIDocumentInteractionControllerDelegate>
{
IBOutlet UIActivityIndicatorView *loading;
IBOutlet UIWebView *Wview;
UIDocumentInteractionController *controller;
}
#property (nonatomic, retain) IBOutlet UIActivityIndicatorView *loading;
#property (nonatomic, retain) IBOutlet UIWebView *Wview;
#property (nonatomic, retain) UIDocumentInteractionController *controller;
-(void)buttonPressed;
-(IBAction)open_in:(id)sender;
-(IBAction)back:(id)sender;
#end
.m file
#import "pdfView.h"
#implementation pdfView
#synthesize loading,Wview;
#synthesize controller;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)viewDidLoad
{
[loading startAnimating];
[super viewDidLoad];
Wview.scalesPageToFit = TRUE;
Wview.multipleTouchEnabled = TRUE;
[Wview setOpaque:NO];
NSString *path = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[Wview loadRequest:request];
[loading stopAnimating];
}
-(IBAction)open_in:(id)sender
{
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
-(IBAction)back:(id)sender
{
[self.view removeFromSuperview];
}
-(void)buttonPressed
{
//[self.view removeFromSuperview];
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:#"guia_seguranca_2" ofType:#"pdf"];
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileToOpen]];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
return self.view.frame;
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
[self.controller autorelease];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[super dealloc];
[Wview release];
[loading release];
}
#end
Thanks in advance.....
I would suggest not useing the webview and using a pdf app (ibook, cloudreader) like this.
//name of pdf
NSString * pathString = #"userguide";
//get pdf path
NSString * filePath = [[NSBundle mainBundle] pathForResource:pathString ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
self.docController = [UIDocumentInteractionController interactionControllerWithURL:url];
BOOL isValid = [self.docController presentOpenInMenuFromRect:self.handBookLaunch.frame inView:self.view animated:YES];
if (!isValid) {
NSString * messageString = [NSString stringWithFormat:#"No PDF reader was found on your device. Please download a PDF reader (eg. iBooks)."];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:messageString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
Solved, added this code for layout verification:
-(void) viewWillAppear:(BOOL)animated
{
CGRect arect=[[UIScreen mainScreen]applicationFrame];
CGRect anotherrect=[[UIApplication sharedApplication]statusBarFrame];
if(self.view.center.y==arect.size.height/2)
self.view.center=CGPointMake(self.view.center.x, self.view.center.y+anotherrect.size.height); // fix silliness in IB that makes view start 20 pixels higher than it should on iPhone
}
source: https://discussions.apple.com/thread/2658315?start=0&tstart=0

show images on tabelview that are come from webservice

I have used the below code. In this code I am showing images that are coming from the webservices. To increase the scroll speed of tabelview I use UIImageView+WebCache it increase the scrolling speed fast but image is show when I touch the imageview. How to show the images when tabelview is display
NSString *str=[self.uploadimagearry objectAtIndex:indexPath.row];
// NSString *str1=[str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *uploadimageURL = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSData *imgdata=[NSData dataWithContentsOfURL:uploadimageURL];
//UIImage * uploadimage = [UIImage imageWithData:imgdata];
cell.imageView.frame=CGRectMake(0, -15, 50, 35);
//[cell.imageView setImageWithURL:uploadimageURL];
[cell.imageView setImageWithURL:uploadimageURL];
You have to start NSUrlConnection in a different run-loop, so that you receive data while the table is scrolling.
Just check out below examples :
LazyTableImages
Lazy loading multiple images on background threads on the iPhone
//JImage.h
#import <Foundation/Foundation.h>
#interface JImage : UIImageView {
NSURLConnection *connection;
NSMutableData* data;
UIActivityIndicatorView *ai;
}
-(void)initWithImageAtURL:(NSURL*)url;
#property (nonatomic, retain) NSURLConnection *connection;
#property (nonatomic, retain) NSMutableData* data;
#property (nonatomic, retain) UIActivityIndicatorView *ai;
#end
//JImage.m
#import "JImage.h"
#implementation JImage
#synthesize ai,connection, data;
-(void)initWithImageAtURL:(NSURL*)url {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self setContentMode:UIViewContentModeScaleToFill];
if (!ai){
[self setAi:[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];
[ai startAnimating];
[ai setFrame:CGRectMake(27.5, 27.5, 20, 20)];
[ai setColor:[UIColor blackColor]];
[self addSubview:ai];
}
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) data = [[NSMutableData alloc] initWithCapacity:5000];
[data appendData:incrementalData];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data length]];
NSLog(#"resourceData length: %d", [resourceLength intValue]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection error...");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[ai removeFromSuperview];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[self setImage:[UIImage imageWithData: data]];
[ai removeFromSuperview];
}
#end
//Include the definition in your class where you want to use the image
-(UIImageView*)downloadImage:(NSURL*)url:(CGRect)frame {
JImage *photoImage=[[JImage alloc] init];
photoImage.backgroundColor = [UIColor clearColor];
[photoImage setFrame:frame];
[photoImage setContentMode:UIViewContentModeScaleToFill];
[photoImage initWithImageAtURL:url];
return photoImage;
}
//How to call the class
UIImageView *imagV=[self downloadImage:url :rect];
//you can call the downloadImage function in looping statement and subview the returned imageview.
//it will help you in lazy loading of images.
//Hope this will help

Populating UITableView dynamically

I have the following code to fetch the data from URL, store it in arrays, and display it inside the table.
Now the issue is my URL which is feeding data to the tables changes according to the button click i.e. If user clicks button [gainer], data gets fetched from URL related to gainer and so on.
As I have called gainer method in didLoad method, initially data is displayed from the respective URL.But on button click no action is taken. The reason is I'm populating the arrays in methods (gainer and looser) but table is fetching data from the arrays at the time of table creation(and arrays are empty at that point).
I have created button in design view while I'm creating table programmatically.
fetchdataViewController.h
#import <UIKit/UIKit.h>
#interface fetchdataViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{
IBOutlet UIWebView *webView;
NSMutableArray *arr1;
NSMutableArray *atarr;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
UITableView *aTableView;
}
-(IBAction)btnClicked:(id)sender;
-(IBAction)btnClicked1:(id)sender;
-(void)gainer;
-(void)looser;
#property(nonatomic,retain)NSMutableArray *arr1;
#property(nonatomic,retain)NSMutableArray *arr2;
#property(nonatomic,retain)NSMutableArray *atarr;
#property(nonatomic,retain)NSMutableArray *a;
#property(nonatomic,retain)NSMutableArray *b;
#property(nonatomic,retain)NSMutableArray *c;
#property(nonatomic,retain)NSMutableArray *d;
#property(nonatomic,retain)UIWebView *webView;
#property(nonatomic,retain)UITableView *aTableView;
#end
fetchdataViewController.m
#import "fetchdataViewController.h"
#implementation fetchdataViewController
NSMutableArray *atarr;
NSMutableArray *arr1;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
NSMutableString *mainstr;
NSMutableString *str;
#synthesize webView;
#synthesize arr1;
#synthesize arr2;
#synthesize atarr;
#synthesize a;
#synthesize b;
#synthesize c;
#synthesize d;
#synthesize aTableView;
int i,j;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [a count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier=#"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
static NSInteger StateTag1 = 3;
static NSInteger StateTag2 = 4;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
CGRect frame;
frame.origin.x = 10;
frame.origin.y = 5;
frame.size.height = 35;
frame.size.width = 170;
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:frame];
capitalLabel.tag = CapitalTag;
[cell.contentView addSubview:capitalLabel];
frame.origin.x += 125;
UILabel *stateLabel = [[UILabel alloc] initWithFrame:frame];
stateLabel.tag = StateTag;
[cell.contentView addSubview:stateLabel];
frame.origin.x += 100;
UILabel *stateLabel1 = [[UILabel alloc] initWithFrame:frame];
stateLabel1.tag = StateTag1;
[cell.contentView addSubview:stateLabel1];
frame.origin.x += 100;
UILabel *stateLabel2 = [[UILabel alloc] initWithFrame:frame];
stateLabel2.tag = StateTag2;
[cell.contentView addSubview:stateLabel2];
}
UILabel *capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
UILabel *stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
UILabel *stateLabel1 = (UILabel *) [cell.contentView viewWithTag:StateTag1];
UILabel *stateLabel2 = (UILabel *) [cell.contentView viewWithTag:StateTag2];
capitalLabel.text=[a objectAtIndex:indexPath.row];
stateLabel.text = [b objectAtIndex:indexPath.row];
stateLabel1.text = [c objectAtIndex:indexPath.row];
stateLabel2.text = [d objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)btnClicked:(id)sender{
[self gainer];
}
-(IBAction)btnClicked1:(id)sender {
[self looser];
}
-(void)gainer{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=G"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
//storing page data in string
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
// NSLog(#"i=:%i",i);
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
-(void)looser{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=L"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
{
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
[self gainer];
[super viewDidLoad];
aTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame] style:UITableViewStyleGrouped];
aTableView.dataSource = self;
aTableView.delegate = self;
aTableView.frame = CGRectMake(0, 10, 720, 500);
[self.view addSubview:aTableView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
UPDATE
When I run the below code, I get this output. That shaded grey portion is my main concern.
THANKS IN ADVANCE
You need to tell your UITableView that the data has changed by calling reloadData.
Use [self.tableview reloadData] after each change of url and with new arrays filled.

open link from UIWebView into Safari (iphone)

ok rather than try to explain my problem in text, watch this little video i recorded
http://www.youtube.com/watch?v=fwb55jnZI6w
and here is the code for the detail view controller (the page where the webview is)
detailViewController.h
#import <UIKit/UIKit.h>
#import "MWFeedItem.h"
#interface DetailViewController : UIViewController <UIWebViewDelegate> {
MWFeedItem *item;
NSString *summaryString;
IBOutlet UILabel *titleLabel;
IBOutlet UIWebView *contentLabel;
//IBOutlet UILabel *dateLabel;
IBOutlet UIScrollView *textScroller;
}
#property (nonatomic, retain) MWFeedItem *item;
#property (nonatomic, retain) NSString *summaryString;
#property (nonatomic, retain) IBOutlet UILabel *titleLabel;
#property (nonatomic, retain) IBOutlet UIWebView *contentLabel;
#end
detailViewController.m
#import "DetailViewController.h"
#import "NSString+XMLEntities.h"
typedef enum { SectionHeader, SectionDetail } Sections;
typedef enum { SectionHeaderTitle, SectionHeaderDate, SectionHeaderURL } HeaderRows;
typedef enum { SectionDetailSummary } DetailRows;
#implementation DetailViewController
#synthesize item, summaryString, titleLabel, contentLabel;
- (BOOL)webView:(UIWebView *)contentLabel shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
NSURL *requestURL = [ [ request URL ] retain ];
// Check to see what protocol/scheme the requested URL is.
return [ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
return NO;
// Auto release
[ requestURL release ];
// If request url is something other than http or https it will open
// in UIWebView. You could also check for the other following
// protocols: tel, mailto and sms
}
- (void)viewDidLoad {
[super viewDidLoad];
/*if (item.date) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
self.dateString = [formatter stringFromDate:item.date];
[formatter release];
}*/
if (item.summary) {
self.summaryString = [[[item.summary stringByStrippingTags] stringByRemovingNewLinesAndWhitespace] stringByDecodingXMLEntities];
}
titleLabel.text = item.title ? item.title : #"[No Title]";
[titleLabel setBackgroundColor:[UIColor clearColor]];
//dateLabel.text = dateString ? dateString : #"[No Date]";
// Summary
NSString *HTMLData = summaryString;
[contentLabel loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.feed43.com/1515171705611023.xml"]]];
//Calculate the expected size based on the font and linebreak mode of your label
//CGSize maximumLabelSize = CGSizeMake(280,9999);
//CGSize expectedLabelSize = [summaryString sizeWithFont:contentLabel.font
//constrainedToSize:maximumLabelSize
//lineBreakMode:contentLabel.lineBreakMode];
//adjust the label the the new height.
//CGRect newFrame = contentLabel.frame;
//newFrame.size.height = expectedLabelSize.height;
//contentLabel.frame = newFrame;
[textScroller setCanCancelContentTouches:NO];
[textScroller setContentSize:CGSizeMake(320, 500)];
textScroller.indicatorStyle = UIScrollViewIndicatorStyleBlack;
textScroller.scrollEnabled = YES;
textScroller.clipsToBounds = YES;
//return titleLabel;
//return dateLabel;
//return contentLabel;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
//return (interfaceOrientation == UIInterfaceOrientationPortrait);
return NO;
}
- (void)dealloc {
[super dealloc];
}
#end
note: even though it says "contentLabel" it is a UIWebView. it is left over from old versions
Thanks!
Implement -(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
Then you can do something like this :
NSURL* url = [request URL];
if (UIWebViewNavigationTypeLinkClicked == navigationType)
{
[[UIApplication sharedApplication] openURL:url];
return NO;
}