Use Block Based Action Sheet - iphone

I am using this as a bit of a blueprint for setting up a block based action sheet. My actions for the action sheet are Cancel, Download, and Stream. I changed the BlockBasedActionSheet.h to:
#interface BlockBasedActionSheet : UIActionSheet<UIActionSheetDelegate> {
}
#property (copy) void (^cancelBlock)();
#property (copy) void (^downloadBlock)();
#property (copy) void (^streamBlock)();
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle downloadButtonTitle:(NSString *)downloadButtonTitle streamButtonTitle:(NSString *)streamButtonTitle cancelAction:(void (^)())cancelBlock downloadAction:(void (^)())downloadBlock streamAction:(void (^)())streamBlock;
#end
and the BlockBasedActionSheet.m to:
#implementation BlockBasedActionSheet
#synthesize cancelBlock = _cancelBlock, streamBlock = _streamBlock, downloadBlock = _downloadBlock;
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle downloadButtonTitle:(NSString *)downloadButtonTitle streamButtonTitle:(NSString *)streamButtonTitle cancelAction:(void (^)())cancelBlock downloadAction:(void (^)())downloadBlock streamAction:(void (^)())streamBlock
{
self = [super initWithTitle:title delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:nil otherButtonTitles:downloadButtonTitle, streamButtonTitle, nil];
if (self) {
_cancelBlock = Block_copy(cancelBlock);
_downloadBlock = Block_copy(downloadBlock);
_streamBlock = Block_copy(streamBlock);
}
return self;
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSAssert(actionSheet == self, #"Wrong Action Sheet passed");
if (buttonIndex == 0) {
if (self.cancelBlock) {
self.cancelBlock();
}
}
if (buttonIndex == 1) {
if (self.downloadBlock) {
self.downloadBlock();
}
}
if (buttonIndex == 2) {
if (self.streamBlock) {
self.streamBlock();
}
}
}
#end
In my TableView didSelectRowAtIndexPath, I put the following:
BlockBasedActionSheet *askSheet =
[[BlockBasedActionSheet alloc]
initWithTitle:#"What Do You Want To Do" cancelButtonTitle:#"Cancel" downloadButtonTitle:#"Download" streamButtonTitle:#"Stream" cancelAction:^ {
}downloadAction:^ {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
CGRect frame = CGRectMake(0, 49, 160, 50);
progress = [[UIProgressView alloc] initWithFrame:frame];
cell.contentView.tag = 100;
[cell.contentView addSubview:progress];
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:entry.articleUrl];
self.nameit = entry.articleTitle;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}streamAction:^ {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}];
[askSheet showInView:self.tabBarController.view];
[askSheet release];
The Action Sheet Presents from top to bottom:
Download
Stream
Cancel
When I press Download, the Cancel action performs;
Stream, the Download action performs;
Cancel, the Stream Action performs
What have I done wrong that it is getting out of order?

try this:
if (buttonIndex == [self cancelButtonIndex]) {
if (self.cancelBlock) {
self.cancelBlock();
}
}
if (buttonIndex == [self firstOtherButtonIndex]) {
if (self.downloadBlock) {
self.downloadBlock();
}
}
if (buttonIndex == [self firstOtherButtonIndex] +1) {
if (self.streamBlock) {
self.streamBlock();
}
}

Related

Search Bar doesn't work on Device in ios

I created iOS(5.0) application in that I have search Bar, which is used to search the content in server side, while passing keyword entered into search bar the list of content parsed from the xml and shown in Table View,
its working fine in Emulator,.but in device (ipad2 & iphone4s) its not showing table of content were searched.
pls let me know what am making wrong..
Thanks in advance,.
murali.
This is mySearchClass.h
#interface SearchClass : UIViewController<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate,UISearchBarDelegate, UISearchDisplayDelegate>
{
AppDelegate *abc;
MBProgressHUD *HUD;
IBOutlet UIScrollView *scrv;
IBOutlet UITableView *tableV;
UISearchBar *searchBar;
IBOutlet UILabel *lblTitle;
IBOutlet UIActionSheet *actionSheet;
IBOutlet UIPickerView *pickerView;
IBOutlet UIButton *btnActionSheet;
UIToolbar *pickerToolBar;
NSMutableArray *arrCate;
NSString *key;
}
-(void)cleartable;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
#end
//======================
This is my SearchClass.m
#implementation SearchClass
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.image = [UIImage imageNamed:#"search"];
UIImageView *navImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"i-street"]];
self.navigationItem.titleView = navImg;
}
return self;
}
- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg1.png"]];
abc = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//[SearchClass initWithNibName:#"" bundle:nil];
//[SearchClass initWithNibName:#"SearchClass" bundle:nil];
arrCate = [[NSMutableArray alloc]initWithObjects:#"Arts & Entertainment",#"Restaurants",#"Bars, Pubs & Clubs",#"Film and Cinema",#"Live Gigs",#"Shops", nil];
pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 43 , 320, 480)];
pickerView.delegate = self;
pickerView.dataSource = self;
[pickerView setShowsSelectionIndicator:YES];
pickerToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
pickerToolBar.barStyle = UIBarStyleBlackOpaque;
[pickerToolBar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIButton *btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDone setFrame:CGRectMake(0, 0, 60, 30)];
[btnDone addTarget:self action:#selector(closeActionSheet) forControlEvents:UIControlEventTouchUpInside];
[btnDone setBackgroundImage:[UIImage imageNamed:#"done.png"] forState:UIControlStateNormal];
UIBarButtonItem *dbtn = [[UIBarButtonItem alloc]initWithCustomView:btnDone];
[barItems addObject:dbtn];
[pickerToolBar setItems:barItems animated:YES];
}
-(IBAction)closeActionSheet
{
lblTitle.text=[arrCate objectAtIndex:[pickerView selectedRowInComponent:0]];
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [arrCate objectAtIndex:row];
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
return [arrCate count];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
lblTitle.text = [arrCate objectAtIndex:row];
[abc.arrSearch removeAllObjects];
[tableV reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// NSLog(#"table view count seasrch :%d",[abc.arrSearch count]);
return [abc.arrSearch count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *imgUrl;
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if(indexPath.row > 0)
{
UIImageView *separator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"line1.png"]];
[cell.contentView addSubview: separator];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgbest=[[UIImageView alloc]initWithFrame:CGRectMake(213,4,107,64)];
UIActivityIndicatorView *actSpiner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
actSpiner.center = imgbest.center;
[actSpiner startAnimating];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 200, 20)];
lbl.textAlignment = UITextAlignmentLeft;
lbl.font = [UIFont fontWithName:#"Helvetica" size:18.0];
lbl.textColor = [UIColor whiteColor];
lbl.backgroundColor = [UIColor clearColor];
lbl.numberOfLines=0;
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 23, 200, 20)];
lbl1.textAlignment = UITextAlignmentLeft;
lbl1.font = [UIFont fontWithName:#"American Typewriter" size:13.0];
lbl1.textColor = [UIColor whiteColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.numberOfLines=0;
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(5,44, 200, 20)];
lbl2.textAlignment = UITextAlignmentLeft;
lbl2.font = [UIFont fontWithName:#"Helvetica-Oblique" size:12.0];
lbl2.textColor = [UIColor whiteColor];
lbl2.backgroundColor = [UIColor clearColor];
lbl2.numberOfLines=0;
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
ArtsClass *arts=[[ArtsClass alloc]init];
arts = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = arts.artThumpImg;
lbl.text=arts.artTitle;
lbl1.text=arts.artDesc;
lbl2.text=arts.artDate;
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
ResClass *res=[[ResClass alloc]init];
res = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = res.resLogoImg;
lbl.text=res.resName;
lbl1.text=res.resType;
lbl2.text=res.resPopularDish;
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
BarClass *bar=[[BarClass alloc]init];
bar = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = bar.barImg;
lbl.text=bar.barTitle;
lbl1.text=bar.barDesc;
lbl2.text=bar.barFacilities;
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
FilmClass *film=[[FilmClass alloc]init];
film = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = film.filmImg;
lbl.text=film.filmName;
lbl1.text=film.filmSynopsis;
lbl2.text=film.filmReleDate;
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
GigsClass *gigs=[[GigsClass alloc]init];
gigs = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = gigs.eventThumpImg;
lbl.text=gigs.eventTitle;
lbl1.text=gigs.eventCate;
lbl2.text=[NSString stringWithFormat:#"%# - %#",gigs.eventStartDate,gigs.eventEndDate];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
ShopsClass *shops=[[ShopsClass alloc]init];
shops = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = shops.shopThumpImg;
lbl.text=shops.shopName;
lbl1.text=shops.shopDesc;
lbl2.text=shops.shopFacilities;
}
NSURL *url = [NSURL URLWithString:imgUrl] ;
// NSLog(#"image link:%#",url);
dispatch_queue_t currQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(currQueue,^{
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
imgbest.image = [UIImage imageWithData:data];
});
});
[cell addSubview:actSpiner];
[cell addSubview:imgbest];
[cell addSubview:lbl];
[cell addSubview:lbl1];
[cell addSubview:lbl2];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
abc.subClassTag=#"ARTS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Arts & Entertainment";
abc.objArt = [abc.arrArts objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
abc.subClassTag=#"RES";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Restaurants";
abc.objRest = [abc.arrRes objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
abc.subClassTag=#"BAR";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Bars, Pubs & Clubs";
abc.objBar = [abc.arrBars objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
abc.subClassTag=#"FILMS";
abc.classTag = #"PLAYERCLASS";
abc.strTitle = #"Film and Cinema";
abc.objFilm = [abc.arrFilm objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
abc.subClassTag=#"GIGS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Live Gigs";
abc.objGig = [abc.arrGigs objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
abc.subClassTag=#"SHOPS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Shops";
abc.objShop = [abc.arrShops objectAtIndex:indexPath.row];
}
if([abc.classTag isEqualToString:#"PLAYERCLASS"])
{
PlayerClass *pl = [[PlayerClass alloc]init];
[self.navigationController pushViewController:pl animated:YES];
}
else if([abc.classTag isEqualToString:#"GALLERYCLASS"])
{
GalaryClass *gc = [[GalaryClass alloc]init];
[self.navigationController pushViewController:gc animated:YES];
}
}
- (void)viewDidUnload
{
scrv = nil;
tableV = nil;
searchBar = nil;
lblTitle = nil;
[super viewDidUnload];
}
-(IBAction)getCategory:(id)sender
{
[searchBar resignFirstResponder];
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil //#"Done"
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setTag:0];
[actionSheet addSubview:pickerView];
[actionSheet showInView:self.view.superview];
[actionSheet addSubview:pickerToolBar];
[actionSheet showInView:self.view.superview];
[actionSheet setBounds:CGRectMake(0, 0, 320, 430)];
}
-(void)cleartable
{
NSArray * ar=[tableV subviews];
for(int j=0;j<ar.count;j++)
{
NSArray *arr=[[ar objectAtIndex:j]subviews];
for(int i=0;i<arr.count;i++)
{
if([[arr objectAtIndex:i]isKindOfClass:[UILabel class]])
{
[[arr objectAtIndex:i]removeFromSuperview];
}
}
}
}
-(void)showProgress
{
//[searchBar resignFirstResponder];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
// Set the hud to display with a color
HUD.color = [UIColor colorWithPatternImage:[UIImage imageNamed:#"box4"]];//[UIColor colorWithRed:0.23 green:0.50 blue:0.82 alpha:0.90];
// HUD.opacity =
HUD.delegate = self;
[HUD showWhileExecuting:#selector(download) onTarget:self withObject:nil animated:YES];
}
-(void)download
{
if([NetworkManager checkForNetworkStatus])
{
ParserClass *p =[[ParserClass alloc]init];
NSLog(#"search bar text %# --- %#",key,lblTitle.text);
if (lblTitle.text==#"Arts & Entertainment")
{
[p search:1 string:key];
}else if(lblTitle.text==#"Restaurants")
{
[p search:5 string:key];
}else if(lblTitle.text==#"Bars, Pubs & Clubs")
{
[p search:4 string:key];
}else if(lblTitle.text==#"Film and Cinema")
{
[p search:2 string:key];
}else if(lblTitle.text==#"Live Gigs")
{
[p search:3 string:key];
}else if(lblTitle.text==#"Shops")
{
[p search:6 string:key];
}
[tableV reloadData];
}
else
{
UIAlertView *alrt = [[UIAlertView alloc]initWithTitle:#"Network Error!" message:#"Please Check your Network connetion.." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alrt show];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}
- (void)searchBar:(UISearchBar *)searchBar1 textDidChange:(NSString *)searchText
{
if(![lblTitle.text isEqualToString:#"Select Category"])
{
if(searchBar.text.length > 0)
{
key = searchText;
[self showProgress];
// ParserClass *p =[[ParserClass alloc]init];
// NSLog(#"search bar text %# --- %#",searchText,lblTitle.text);
// if (lblTitle.text==#"Arts & Entertainment")
// {
// [p search:1 string:searchText];
// }else if(lblTitle.text==#"Restaurants")
// {
// [p search:5 string:searchText];
// }else if(lblTitle.text==#"Bars, Pubs & Clubs")
// {
// [p search:4 string:searchText];
// }else if(lblTitle.text==#"Film and Cinema")
// {
// [p search:2 string:searchText];
// }else if(lblTitle.text==#"Live Gigs")
// {
// [p search:3 string:searchText];
// }else if(lblTitle.text==#"Shops")
// {
// [p search:6 string:searchText];
// }
//
// [tableV reloadData];
}
else
{
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:nil message:#"Please Give me some Key words..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert1 show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:#"Please Select any Category..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
#end
Thanks for ur Reply,.
Murali.
wrong string comparison
if (lblTitle.text==#"Arts & Entertainment")
it should be like this - try this it must work & let me know.
if (lblTitle.text isEqualToString:#"Arts & Entertainment")
I am also having some issues in my search class, i am using JSON url.
Where is the Parsing URL, what are the fields in the xml.
Check your parsing url in ur local browser by manual append method using query string ,working or not.
check by trace path, use console log for print the URL.
Check if u are using localhost url in ur program somewhere else.
Check your delegate for search class.
use this link for your reference.
https://iphonedevsdk.com/forum/iphone-sdk-development/50468-xml-table-view-searchbar.html

Webview content is not readable after stop animating loading image

I am building one iPhone application where I have two views one for login view and another for web view. When user enters the login credentials, then it will redirect to web view. while loading the webview from login view too much time is taking to load. hence I used alertview to show loading image.
#interface FocusViewController ()
#end
#implementation FocusViewController
#synthesize txtsecurecode;
#synthesize webView;
#synthesize OrganizationCode;
UIActivityIndicatorView *indicator;
UIAlertView *alert;
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (FocusAppDelegate *)[[UIApplication sharedApplication]delegate];
if(appDelegate.data.strOrganizationCode == nil || appDelegate.data.strAccessCode == nil)
{
NSLog(#"YOUR FIRST SCREEN");
_loginView.hidden = NO;
webView.hidden = YES;
}
else
{
NSLog(#"LOAD WEBVIEW DIRECTLY\n");
NSLog(#"Organization Code -> %# \n Secure Access Code -> %#",appDelegate.data.strOrganizationCode,appDelegate.data.strAccessCode);
OrganizationCode.text = appDelegate.data.strOrganizationCode ;
txtsecurecode.text = appDelegate.data.strAccessCode;
[self loginClicked:nil];
webView.hidden = NO;
_loginView.hidden = YES;
}
}
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtsecurecode text] isEqualToString:#""] || [[OrganizationCode text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Access code" :#"Login Failed!":0];
}
else
{
NSString *post =[[NSString alloc] initWithFormat:#"txtsecurecode=%# #&password=%#",[txtsecurecode text],[OrganizationCode text]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/AccountService/security/ValidateAccess?accesscode=%#&companycode=%#&type=1", txtsecurecode.text, OrganizationCode.text]];
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
if([responseData isEqualToString:#""]){
[self alertStatus:#"Please enter valid Access Code" :#"Login Failed !" :0];
}
else
{
appDelegate.data.strOrganizationCode = OrganizationCode.text;
appDelegate.data.strAccessCode = txtsecurecode.text;
[FocusAppDelegate addCustomObjectToUserDefaults:appDelegate.data key:kCredentails];
//Updated
_loginView.hidden = YES;
webView.hidden = NO;
responseData = [responseData stringByReplacingOccurrencesOfString:#" "" " withString:#""];
NSString* encodedString = [responseData stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#" ,encodedString);
alert = [[[UIAlertView alloc] initWithTitle:#"Loading\nPlease Wait..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
indicator.center = CGPointMake(alert.bounds.size.width / 2, alert.bounds.size.height - 50);
[indicator startAnimating];
[alert addSubview:indicator];
[indicator release];
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
webView.delegate = self;
webView.frame = self.view.bounds;
NSString* urlTwo = [[encodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:#"%22" withString:#""];
NSURL *url2;
if([urlTwo hasPrefix:#"http://"]){
url2 = [NSURL URLWithString:urlTwo];
}else{
url2 = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#" , urlTwo]];
}
NSLog(#"url2:%#", url2);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[webView loadRequest:requestObj];
[[self view] addSubview:webView];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!" :0];
}
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(#"webViewDidStartLoad");
[self.view addSubview:self.indicator];
alert.hidden = NO;
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"webViewDidFinishLoad");
[self.indicator removeFromSuperview];
[self.alert dismissWithClickedButtonIndex:1 animated:NO] ;
}
- (IBAction)backgroundClick:(id)sender
{
[txtsecurecode resignFirstResponder];
[OrganizationCode resignFirstResponder];
}
#end
Until content in webview displays, loading image is displaying and working good. but content of webview is not editable and remaining static as I think I used 'web view.hidden = YES'. when I comment the alert method and run then content of webview is also editable and working good as required. I need to load the content of url after loading image stops loading.
I would suggest show the activity indicator from the Viewcontroller having the WebView and implement the WebView Delegate methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[actvityIndicator startAnimating];
}
and
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[actvityIndicator stopAnimating];
}
this will keep your webview Interactive and also show the indicator till the page loads completely
you can try something like this. The Delegate is important in .h file
FocusViewController.h
#interface FocusViewController : UIViewController <UIWebViewDelegate> {
UIActivityIndicatorView *indicator;
}
FocusViewController.m
- (void)viewDidLoad
{
// Loading Indicator
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[indicator setColor:[UIColor colorWithRed:50.0/255.0 green:120.0/255.0 blue:200.0/255.0 alpha:1.0]];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[indicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[indicator stopAnimating];
}

Three20 to save images?(Close)

i'm a new iPhone application developer,i need create one application like photo gallery.Now my problem is i donno how to save a image to photo album.
i have build my project is no error no werning to me.in my simulator can run the project.
But i cnt see any things i add.Hope can help me.Thanks.
my code here.
Three20PhotoDemoAppDelegate.h
#import <UIKit/UIKit.h>
#interface Three20PhotoDemoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
Three20PhotoDemoAppDelegate.m
#import "Three20PhotoDemoAppDelegate.h"
#import "AlbumController.h"
#import <Three20/Three20.h>
#implementation Three20PhotoDemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"demo://album" toViewController: [AlbumController class]];
[navigator openURLAction:[TTURLAction actionWithURLPath:#"demo://album"]];
return YES;
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
[[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
return YES;
}
- (void)dealloc {
[super dealloc];
}
#end
PhotoSource.h
#import <Three20/Three20.h>
#import <Three20/Three20+Additions.h>
typedef enum {
PhotoSourceNormal = 0,
PhotoSourceDelayed = 1,
PhotoSourceVariableCount = 2,
PhotoSourceLoadError = 4,
} PhotoSourceType;
#interface PhotoSource : TTURLRequestModel <TTPhotoSource> {
PhotoSourceType _type;
NSString* _title;
NSMutableArray* _photos;
NSArray* _tempPhotos;
NSTimer* _fakeLoadTimer;
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title
photos:(NSArray*)photos photos2:(NSArray*)photos2;
#end
PhotoSource.m
import "PhotoSource.h"
#implementation PhotoSource
#synthesize title = _title;
- (void)fakeLoadReady {
_fakeLoadTimer = nil;
if (_type & PhotoSourceLoadError) {
[_delegates makeObjectsPerformSelector: #selector(model:didFailLoadWithError:)
withObject: self
withObject: nil];
} else {
NSMutableArray* newPhotos = [NSMutableArray array];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
[newPhotos addObject:photo];
}
}
[newPhotos addObjectsFromArray:_tempPhotos];
TT_RELEASE_SAFELY(_tempPhotos);
[_photos release];
_photos = [newPhotos retain];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
[_delegates makeObjectsPerformSelector:#selector(modelDidFinishLoad:) withObject:self];
}
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title photos:(NSArray*)photos
photos2:(NSArray*)photos2 {
if (self = [super init]) {
_type = type;
_title = [title copy];
_photos = photos2 ? [photos mutableCopy] : [[NSMutableArray alloc] init];
_tempPhotos = photos2 ? [photos2 retain] : [photos retain];
_fakeLoadTimer = nil;
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
if (!(_type & PhotoSourceDelayed || photos2)) {
[self performSelector:#selector(fakeLoadReady)];
}
}
return self;
}
- (id)init {
return [self initWithType:PhotoSourceNormal title:nil photos:nil photos2:nil];
}
- (void)dealloc {
[_fakeLoadTimer invalidate];
TT_RELEASE_SAFELY(_photos);
TT_RELEASE_SAFELY(_tempPhotos);
TT_RELEASE_SAFELY(_title);
[super dealloc];
}
- (BOOL)isLoading {
return !!_fakeLoadTimer;
}
- (BOOL)isLoaded {
return !!_photos;
}
- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
if (cachePolicy & TTURLRequestCachePolicyNetwork) {
[_delegates makeObjectsPerformSelector:#selector(modelDidStartLoad:) withObject:self];
TT_RELEASE_SAFELY(_photos);
_fakeLoadTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(fakeLoadReady) userInfo:nil repeats:NO];
}
}
- (void)cancel {
[_fakeLoadTimer invalidate];
_fakeLoadTimer = nil;
}
- (NSInteger)numberOfPhotos {
if (_tempPhotos) {
return _photos.count + (_type & PhotoSourceVariableCount ? 0 : _tempPhotos.count);
} else {
return _photos.count;
}
}
- (NSInteger)maxPhotoIndex {
return _photos.count-1;
}
- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
if (photoIndex < _photos.count) {
id photo = [_photos objectAtIndex:photoIndex];
if (photo == [NSNull null]) {
return nil;
} else {
return photo;
}
} else {
return nil;
}
}
#end
Photo.h
#import <Three20/Three20.h>
#interface Photo : NSObject <TTPhoto> {
id<TTPhotoSource> _photoSource;
NSString* _thumbURL;
NSString* _smallURL;
NSString* _URL;
CGSize _size;
NSInteger _index;
NSString* _caption;
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption;
#end
Photo.m
#import "Photo.h"
#implementation Photo
#synthesize photoSource = _photoSource, size = _size, index = _index, caption = _caption;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size {
return [self initWithURL:URL smallURL:smallURL size:size caption:nil];
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption {
if (self = [super init]) {
_photoSource = nil;
_URL = [URL copy];
_smallURL = [smallURL copy];
_thumbURL = [smallURL copy];
_size = size;
_caption;
_index = NSIntegerMax;
}
return self;
}
- (void)dealloc {
TT_RELEASE_SAFELY(_URL);
TT_RELEASE_SAFELY(_smallURL);
TT_RELEASE_SAFELY(_thumbURL);
TT_RELEASE_SAFELY(_caption);
[super dealloc];
}
- (void)viewDidLoad {
}
- (NSString*)URLForVersion:(TTPhotoVersion)version {
if (version == TTPhotoVersionLarge) {
return _URL;
} else if (version == TTPhotoVersionMedium) {
return _URL;
} else if (version == TTPhotoVersionSmall) {
return _smallURL;
} else if (version == TTPhotoVersionThumbnail) {
return _thumbURL;
} else {
return nil;
}
}
#end
AlbumController.h
#import <Three20/Three20.h>
#interface AlbumController : TTPhotoViewController <UIActionSheetDelegate>{
NSArray *images;
UIBarButtonItem *_clickActionItem;
UIToolbar *_toolbar;
}
#property (nonatomic, retain) NSArray *images;
#property (nonatomic, retain) UIBarButtonItem *_clickActionItem;
#property (nonatomic, retain) UIToolbar *_toolbar;
#end
AlbumController.m
#import "AlbumController.h"
#import "PhotoSource.h"
#import "Photo.h"
#implementation AlbumController
#synthesize images;
- (void)loadView {
CGRect screenFrame = [UIScreen mainScreen].bounds;
self.view = [[[UIView alloc] initWithFrame:screenFrame]
autorelease];
CGRect innerFrame = CGRectMake(0, 0,
screenFrame.size.width,
screenFrame.size.height);
_innerView = [[UIView alloc] initWithFrame:innerFrame];
_innerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_innerView];
_scrollView = [[TTScrollView alloc] initWithFrame:screenFrame];
_scrollView.delegate = self;
_scrollView.dataSource = self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[_innerView addSubview:_scrollView];
UIBarButtonItem *_actionButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/imageAction.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(popupActionSheet)];
_nextButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/nextIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(nextAction)];
_previousButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/previousIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(previousAction)];
UIBarButtonItem* playButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemPlay target:self action:#selector
(playAction)] autorelease];
playButton.tag = 1;
UIBarItem* space = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
autorelease];
_toolbar = [[UIToolbar alloc] initWithFrame:
CGRectMake(0, screenFrame.size.height - TT_ROW_HEIGHT,
screenFrame.size.width, TT_ROW_HEIGHT)];
_toolbar.barStyle = self.navigationBarStyle;
_toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleTopMargin;
_toolbar.items = [NSArray arrayWithObjects:
_actionButton, space, _previousButton, space,
_nextButton, space, nil];
[_innerView addSubview:_toolbar];
}
//(Just to add an action sheet)
//At the bottom of that codefile -- I added:
-(void)popupActionSheet {
UIActionSheet *popupQuery = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Save Image",nil];
popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[popupQuery showInView:self.view];
[popupQuery release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:
(int)buttonIndex {
//UIImage* image = [[TTURLCache sharedCache] imageForURL:imageURL];
if (buttonIndex==0){
UIImage* thisImage = [[TTURLCache sharedCache] imageForURL:
[_centerPhoto URLForVersion:TTPhotoVersionLarge]];
UIImageWriteToSavedPhotosAlbum(thisImage, nil, nil, nil);
//{UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"URL"
//message:[_centerPhoto URLForVersion:TTPhotoVersionLarge] delegate:self cancelButtonTitle:#"No" ,otherButtonTitles:#"Yes", nil];
//[alert show];}
}
}
-(void)createPhotos {
images = [[NSArray alloc] initWithObjects:
[[[Photo alloc] initWithURL:#"bundle://14.png" smallURL:#"bundle://14.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://30.png" smallURL:#"bundle://30.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://back.jpeg" smallURL:#"bundle://back.jpeg"
size:CGSizeMake(319, 317)] autorelease],
nil];
}
- (void)viewDidLoad {
//[self loadView];
[self createPhotos]; // method to set up the photos array
self.photoSource = [[PhotoSource alloc]
initWithType:PhotoSourceNormal
title:#"SexyGirl"
photos:images
photos2:nil
];
}
#end
If all you need is to save an image to the Photos album, you can use:
UIImage *myImage;
UIImageWriteToSavedPhotosAlbum(myImage,nil,nil,nil);
If this is not your problem, then I don't get it. If you don't tell us where the problem is, posting three pages worth of code is pretty useless.

iphone Dev - activity indicator with NSThread not working on Nav controller table view

I really can't get this to work, basically when my JSON feeds loads I want the indicator to show, then hide when it's stopped.
It loads top level menu items 1st "Publishing, Broadcasting, Marketing Services", then when Broadcasting is selected it loads a feed using the JSON framework hosted on Google. Round this load I call startIndicator and stopIndicator using the NSThread. Have I missed something?
#implementation GeneralNewsTableViewController
#synthesize dataList;
#synthesize generalNewsDetailViewController;
#synthesize atLevel;
-(void) startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
[pool release];
}
-(void) stopIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView stopAnimating];
[pool release];
}
- (void)viewDidLoad {
NSMutableArray *checker = self.dataList;
if(checker == nil)
{
self.title = NSLocalizedString(#"General1",#"General News");
NSMutableArray *array = [[NSArray alloc] initWithObjects:#"Publishing", #"Broadcasting",#"Marketing Services",nil];
self.dataList = [array retain];
self.atLevel = #"level1";
[array release];
}
UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//set the initial property
[activityIndicator stopAnimating];
[activityIndicator hidesWhenStopped];
//Create an instance of Bar button item with custome view which is of activity indicator
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
//Set the bar button the navigation bar
[self navigationItem].rightBarButtonItem = barButton;
//Memory clean up
[activityIndicator release];
[barButton release];
[super viewDidLoad];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
return 70.0f;
}
else
{
return 40.0f;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *FirstLevelCell = #"FirstLevelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstLevelCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:FirstLevelCell] autorelease];
}
NSInteger row = [indexPath row];
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
NSMutableArray *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
cell.textLabel.text = #"";
}
else
{
cell.textLabel.text = [stream valueForKey:#"title"];
}
cell.textLabel.numberOfLines = 2;
cell.textLabel.font =[UIFont systemFontOfSize:10];
cell.detailTextLabel.numberOfLines = 1;
cell.detailTextLabel.font= [UIFont systemFontOfSize:8];
cell.detailTextLabel.text = [stream valueForKey:#"created"];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.website.co.uk/images/stories/img.jpg"]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
cell.imageView.image = newsImage;
[imageURL release];
[newsImage release];
}
else
{
cell.textLabel.text = [dataList objectAtIndex:row];
}
return cell;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSMutableString *levelType = (NSMutableString *) [dataList objectAtIndex:row];
if(![levelType isKindOfClass:[NSString class]])
{
if(self.generalNewsDetailViewController == nil)
{
GeneralNewsDetailViewController *generalDetail = [[GeneralNewsDetailViewController alloc] initWithNibName:#"GeneralNewsDetailView" bundle:nil];
self.generalNewsDetailViewController = generalDetail;
[generalDetail release];
}
NSDictionary *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
generalNewsDetailViewController.newsTitle = #"";
}
else
{
generalNewsDetailViewController.newsTitle =[stream valueForKey:#"title"];
}
generalNewsDetailViewController.newsId = [stream valueForKey:#"id"];
generalNewsDetailViewController.fullText = [stream valueForKey:#"fulltext"];
generalNewsDetailViewController.newsImage = [stream valueForKey:#"images"];
generalNewsDetailViewController.created = [stream valueForKey:#"created"];
HowDo_v1AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.generalNewsNavController pushViewController:self.generalNewsDetailViewController animated:YES];
}
else
{
GeneralNewsTableViewController
*generalSubDetail = [[GeneralNewsTableViewController alloc] initWithNibName:#"GeneralNewsTableView" bundle:nil];
NSMutableArray *array;
NSString *titleSelected = (NSString *) [dataList objectAtIndex:row];
if([titleSelected isEqualToString:#"Publishing"])
{
generalSubDetail.title = #"Publishing news detail";
array = [[NSArray alloc] initWithObjects:#"pub News1", #"pub News2",#"pub News3",nil];
generalSubDetail.atLevel = #"level1";
}
else if ([titleSelected isEqualToString:#"Broadcasting"])
{
generalSubDetail.title = #"Broadcasting news detail";
/// START
[self performSelectorOnMainThread:#selector(startIndicator) withObject:nil waitUntilDone:YES];
if(jSONDataAccessWrapper == nil)
{
jSONDataAccessWrapper = [JSON_DataAccess_Wrapper alloc];
}
array = [jSONDataAccessWrapper downloadJSONFeed];
[self performSelectorOnMainThread:#selector(stopIndicator) withObject:nil waitUntilDone:YES];
generalSubDetail.atLevel = #"level2";
}
else if ([titleSelected isEqualToString:#"Marketing Services"])
{
generalSubDetail.title = #"Marketing Services news detail";
array = [[NSArray alloc] initWithObjects:#"Marketing News1", #"Marketing News2",#"Marketing News3",nil];
generalSubDetail.atLevel = #"level1";
}
generalSubDetail.dataList = array;
[self.navigationController pushViewController:generalSubDetail animated:YES];
[titleSelected release];
}
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
//- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSIndexPath *) section
{
return [self.dataList count];
}
Cheers for any feedback
Frames
It is usually recommended by Apple that operations on user interface should be done on the main thread.
What you can do is to defer the callback into the main thread:
- (void)startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(startAnimating:) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)startAnimating:(id)sender
{
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
}
Check out the Thread Guide from Apple. It contains useful information.

iphoneSDK: UINavigationController Back button is causing app to crash

My app is crashing when I move between ViewControllers. This is the sequence that causes the crash salesViewController displays confirmViewController. When I press the back button in confirmViewController to go back to salesViewController, the application crashes.
I am not sure why. Here is the code for both of the controllers.
Thanks in advance.
#import "salesViewController.h"
#implementation salesViewController
#synthesize txtCardNumber;
#synthesize txtExpires;
#synthesize txtGrandTotal;
#synthesize txtZip;
#synthesize txtEmail;
#synthesize txtCCV2;
#synthesize txtInvoice;
//#synthesize button;
#synthesize strSaleType;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
}
return self;
}
-(IBAction)btnTipCalculator:(id)sender
{
NSLog(#"I was pressed");
tipCalcViewController *tipVC = [[tipCalcViewController alloc] initWithNibName:#"tipCalcView" bundle:nil];
tipVC.delegate = self;
tipVC.passedTotal = txtGrandTotal.text;
[self presentModalViewController:tipVC animated:YES];
[tipVC release];
}
-(IBAction)btnDateSelector:(id)sender
{
NSLog(#"I was pressed");
DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:#"datePickerView" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
}
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
txtExpires.text = chosenDate;
//do processing here... for example let's set the text of the button to the chosen date
//[button setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
//callback for modal tipCalculator
-(void)tipCalcViewController:(tipCalcViewController *)controller didChooseTip:(NSString *)chosenTip
{
NSString *strNewTotal = chosenTip;
//close tip calculator
[self dismissModalViewControllerAnimated:YES];
//update GUI
txtGrandTotal.text = strNewTotal;
}
-(void)btnSubmitClicked
{
NSURL *url = [NSURL URLWithString:#"https://www.eProcessingNetwork.Com/cgi-bin/tdbe/transact.pl"];
//NSURL *url = [NSURL URLWithString:#"https://www.eprocessingnetwork.com/Reflect/Post.pl"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc]
initWithURL:url] autorelease];
//get settings
//NSUserDefaults *options = [NSUserDefaults standardUserDefaults];
//NSString *acctNumber = [options stringForKey:#"accountNumber"];
//NSString *restrictKey = [options stringForKey:#"restrictKey"];
//uncomment for actual
//[request setPostValue:acctNumber forKey:#"ePNAccount"];
//[request setPostValue:restrictKey forKey:#"RestrictKey"];
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
//FOR TESTING ONLY: UNCOMMENT ABOVE FOR ACTUAL ACCOUNT
[request setPostValue:#"080880" forKey:#"ePNAccount"];
[request setPostValue:#"yFqqXJh9Pqnugfr" forKey:#"RestrictKey"];
}
//FOR TESTING ONLY: UNCOMMENT ABOVE FOR ACTUAL ACCOUNT
[request setPostValue:#"080880" forKey:#"ePNAccount"];
[request setPostValue:#"yFqqXJh9Pqnugfr" forKey:#"RestrictKey"];
//transaction type
if([strSaleType compare:#"Sale"] == NSOrderedSame)
{
[request setPostValue:#"Sale" forKey:#"TranType"];
}
if([strSaleType compare:#"Refund"] == NSOrderedSame)
{
[request setPostValue:#"Return" forKey:#"TranType"];
}
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
[request setPostValue:#"Sale" forKey:#"TranType"];
}
//request no HTML output
[request setPostValue:#"No" forKey:#"HTML"];
//needed to get transID for signature capture
[request setPostValue:#"report" forKey:#"Inv"];
//card number
[request setPostValue:txtCardNumber.text forKey:#"CardNo"];
//parse date
NSString *strDateFull = txtExpires.text;
NSString *strMonth = [strDateFull substringWithRange: NSMakeRange(0, 2)];
NSString *strYear = [strDateFull substringWithRange: NSMakeRange(3, 2)];
//expire month
[request setPostValue:strMonth forKey:#"ExpMonth"];
//expire year
[request setPostValue:strYear forKey:#"ExpYear"];
//total, send as you would write it. no dollar sign needed
[request setPostValue:txtGrandTotal.text forKey:#"Total"];
//address - this makes TBDE ignore requests with no address
[request setPostValue:#"1" forKey:#"SKIP_MISSING"];
//zip
[request setPostValue:txtZip.text forKey:#"Zip"];
//ccv2
[request setPostValue:#"CVV2Type" forKey:#"1"];
[request setPostValue:txtCCV2.text forKey:#"123"];
//email
[request setPostValue:txtEmail.text forKey:#"EMail"];
//invoice # - optional
[request setPostValue:txtInvoice.text forKey:#"Invoice"];
//blocking of course
[request start];
// get confirmation
confirmViewController *anotherViewController = [[confirmViewController alloc] initWithNibName:#"confirmView" bundle:nil];
//set properties
anotherViewController.strConfirmation = [request responseString];
anotherViewController.strCardNumber = txtCardNumber.text;
anotherViewController.strExpires = txtExpires.text;
anotherViewController.strAmount = txtGrandTotal.text;
[self.navigationController pushViewController:anotherViewController animated:YES];
//reset interface
if([anotherViewController.strApproval compare:#"""Y"] == NSOrderedSame)
{
txtCardNumber.text = #"";
txtExpires.text = #"";
txtGrandTotal.text = #"";
txtZip.text = #"";
txtCCV2.text = #"";
txtEmail.text = #"";
txtInvoice.text = #"";
}
[anotherViewController release];
/*
//display the results
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info"
message:[request responseString]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
*/
}
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//Needed to get events
[txtCardNumber setDelegate:self];
[txtExpires setDelegate:self];
[txtGrandTotal setDelegate:self];
[txtZip setDelegate:self];
[txtEmail setDelegate:self];
[txtCCV2 setDelegate:self];
[txtInvoice setDelegate:self];
//adjust title depending on sale type
if([strSaleType compare:#"Sale"] == NSOrderedSame)
{
self.title = #"Sales";
NSLog(#"Passed in sale type: %#", strSaleType );
}
if([strSaleType compare:#"Refund"] == NSOrderedSame)
{
self.title = #"Refunds";
NSLog(#"Passed here in sale type: %#", strSaleType );
}
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
self.title = #"Testing";
NSLog(#"Passed in sale type: %#", strSaleType );
}
//add additional button
UIBarButtonItem *submitButton = [[UIBarButtonItem alloc] initWithTitle:#"Submit" style:UIBarButtonItemStylePlain target:self action:#selector(btnSubmitClicked)];
self.navigationItem.rightBarButtonItem = submitButton;
[submitButton release];
}
- (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 {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
if(txtCardNumber != NULL)
{
[txtCardNumber release];
}
if(txtExpires != NULL)
{
[txtExpires release];
}
if(txtGrandTotal != NULL)
{
[txtGrandTotal release];
}
if(txtZip != NULL)
{
[txtZip release];
}
if(txtEmail != NULL)
{
[txtEmail release];
}
if(txtCCV2 != NULL)
{
[txtCCV2 release];
}
if(txtInvoice != NULL)
{
[txtInvoice release];
}
if(strSaleType != NULL)
{
[strSaleType release];
}
[super dealloc];
}
#end
#import "confirmViewController.h"
#implementation confirmViewController
#synthesize lblStatus;
#synthesize lblCardType;
#synthesize lblCardNumber;
#synthesize lblExpires;
#synthesize lblAmount;
#synthesize lblApproval;
#synthesize strConfirmation;
#synthesize strCardNumber;
#synthesize strExpires;
#synthesize strAmount;
#synthesize strApproval;
-(void)btnSignatureClicked
{
sigCaptureViewController *anotherViewController = [[sigCaptureViewController alloc] initWithNibName:#"sigCaptureView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//prepare confirmation, all that is needed is the first string
NSArray *strings = [strConfirmation componentsSeparatedByString: #","];
NSString *strPreParsed = [strings objectAtIndex:0];
//break out yes/no so we can set status
//NSString *strYesNO = [strPreParsed substringToIndex:2];
NSString *strYesOrNo = [strPreParsed substringWithRange: NSMakeRange(1, 1)];
//save approval for later
strApproval = strYesOrNo;
//debug
NSLog(#"strNo= %#",strYesOrNo);
NSLog(#"strPreParsed= %#", strPreParsed);
//set results
if([strYesOrNo compare:#"Y"] == NSOrderedSame)
{
lblStatus.text = #"Approved";
lblStatus.textColor = [UIColor greenColor];
}
if([strYesOrNo compare:#"N"] == NSOrderedSame)
{
lblStatus.text = #"Declined";
lblStatus.textColor = [UIColor redColor];
}
if([strYesOrNo compare:#"U"] == NSOrderedSame)
{
lblStatus.text = #"Try Again";
lblStatus.textColor = [UIColor redColor];
}
//set card type
if([lblCardNumber.text compare:#"4"] == NSOrderedSame)
{
lblCardType.text = #"Visa";
}
if([lblCardNumber.text compare:#"5"] == NSOrderedSame)
{
lblCardType.text = #"Master";
}
if([lblCardNumber.text compare:#"6"] == NSOrderedSame)
{
lblCardType.text = #"Discover";
}
//set cardnumber
lblCardNumber.text = strCardNumber;
//set expires
lblExpires.text = strExpires;
//set amount
lblAmount.text = strAmount;
//set approval string
lblApproval.text = strPreParsed;
//add signature button
UIBarButtonItem *signatureButton = [[UIBarButtonItem alloc] initWithTitle:#"Signature" style:UIBarButtonItemStylePlain target:self action:#selector(btnSignatureClicked)];
self.navigationItem.rightBarButtonItem = signatureButton;
[signatureButton release];
//set title
self.title = #"Approval";
}
- (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 {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
if(lblCardType != NULL)
{
[lblCardType release];
}
if(lblCardNumber != NULL)
{
[lblCardNumber release];
}
if(lblExpires != NULL)
{
[lblExpires release];
}
if(lblAmount != NULL)
{
[lblAmount release];
}
if(lblApproval != NULL)
{
[lblApproval release];
}
if(lblStatus != NULL)
{
[lblStatus release];
}
if(strConfirmation != NULL)
{
[strConfirmation release];
}
if(strCardNumber != NULL)
{
[strCardNumber release];
}
if(strExpires != NULL)
{
[strExpires release];
}
if(strAmount != NULL)
{
[strAmount release];
}
if(strApproval != NULL)
{
[strApproval release];
}
[super dealloc];
}
#end
I think you are releasing properties that should not be released, for instance you create strYesOrNo like this:
NSString *strYesOrNo = [strPreParsed substringWithRange: NSMakeRange(1, 1)];
without allocating the string. So the string belongs to the viewDidLoad function and will be released by this function. But after creating the strYesOrNo you assign it to a class property, like this:
strApproval = strYesOrNo;
By the time you dealloc your viewcontroller you try to release strApproval, but the viewDidLoad allready released this value and you get a bad-access. You can solve this problem by allocating the memory for strApproval like:
strApproval = [[NSString alloc] initWithString:strYesOrNo];
I did not go through all your code so maybe this is also true for some other properties. Hope this helped.