add a countdown, display the time and fire an action - iphone

Hi I am a beginner in programming
I have already created a tapping application, displaying the tap count after pressing the result button
I want to add a NSTimer, counting 30 second after the first tap (after the tap button was pressed for the first time).
at the same time, displaying the time count down on a label (UILabel timeLabel)
and after 30 second, the tap count will restart to 0.
Please kindly tell me if I need to post anything other than the following, Thanks!!
Here is my .h file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#import <AudioToolbox/AudioToolbox.h>
#class Player;
#interface Tapping2ViewController : UIViewController
<AVAudioPlayerDelegate>
{
Player *aPlayer;
IBOutlet UILabel *timerLabel;
IBOutlet UILabel *resultLabel;
AVAudioPlayer *buttonPlayer;
NSTimer *lv1Timer;
NSInteger *counter1;
}
- (IBAction)addTap:(id)sender;
- (IBAction)getResult:(id)sender;
-(void)restartTapCount;
-(void)start;
#property (retain) NSTimer *lv1Timer;
#property (nonatomic, retain) IBOutlet UILabel *timerLabel;
#end
and my .M file
#import "Tapping2ViewController.h"
#import "Player.h"
#implementation Tapping2ViewController
#synthesize lv1Timer;
#synthesize timerLabel;
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)dealloc
{
[resultLabel release];
[lv1Timer release];
[aPlayer release];
[timerLabel release];
[super dealloc];
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
aPlayer = [[Player alloc] init];
[super viewDidLoad];
}
- (IBAction)addTap:(id)sender
{
//呢到係設定聲音, 首先要用NSSTRING 去 SET 左條路徑先
NSString *buttonFile = [[NSBundle mainBundle] pathForResource:#"button" ofType:#"wav"];
//之後再條NSSTRING 轉做NSURL (因為AVPLAYER 只認URL)
NSURL *buttonFileURL = [NSURL fileURLWithPath:buttonFile];
NSError *error = nil;
//設定AUDIO PLAYER 要播邊條 聲音 *記得SET DELEGATE 做自已去執行
buttonPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:buttonFileURL error:&error];
[buttonPlayer setDelegate:self];
NSLog(#"Before: %d", aPlayer.tapCount);
aPlayer.tapCount++;
//呼叫播放既METHOD
[buttonPlayer play];
NSLog(#"After: %d", aPlayer.tapCount);
/*
//即時顯示數字
aPlayer.result = aPlayer.tapCount;
NSString *sResult = [NSString stringWithFormat:#"%D", aPlayer.result];
resultLabel.text = sResult;
*/
}
- (IBAction)getResult:(id)sender {
aPlayer.result = aPlayer.tapCount;
NSString *aResult = [NSString stringWithFormat:#"%D", aPlayer.result];
resultLabel.text = aResult;
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake)
{
aPlayer.tapCount = 0;
resultLabel.text = #"0";
}
}
- (void)viewDidUnload
{
[resultLabel release];
resultLabel = nil;
[timerLabel release];
timerLabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//下面係PART OF DETECT SHAKE 既METHOD
-(BOOL)canBecomeFirstResponder
{
return YES;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
//去到呢到都係
#end

Here is how I do it in an app, on start :
count = COUNTDOWN_DURATION;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:#selector(countDown)
userInfo:nil repeats:YES];
this will call a countDown method every second. Do whatever you want in that countDown method but make sure to stop the NSTimer on completion (and of course to decrement counter):
if (count < 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
...
count--;

Related

How to add multiple colour in a round progressview after some specific interval in xcode?

I am using a custom progress view in Uiprogressview, and its being filled with a fixed color within 20 seconds, but I want such that it will be filled with the different color after 10 seconds, so that after 2 seconds it will look like a two colored circle,
here is my code:
#import "CEViewController.h"
#interface CEViewController ()
{
}
#end
#implementation CEViewController
#synthesize progressView;
#synthesize progressSlider;
#synthesize playPauseButton;
#synthesize player;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.player = [[[CEPlayer alloc] init] autorelease];
self.player.delegate = self;
UIColor *tintColor = [UIColor orangeColor];
[[UISlider appearance] setMinimumTrackTintColor:tintColor];
[[CERoundProgressView appearance] setTintColor:tintColor];
self.progressView.trackColor = [UIColor colorWithWhite:0.80 alpha:1.0];
self.progressView.startAngle = (3.0*M_PI)/2.0;
}
- (void)viewDidUnload
{
[self setProgressView:nil];
[self setProgressSlider:nil];
[self setPlayPauseButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[progressView release];
[progressSlider release];
self.player = nil;
[playPauseButton release];
[super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)progressSlider:(UISlider *)sender
{
self.player.position = sender.value;
self.progressView.progress = sender.value;
}
- (IBAction)playPauseButton:(UIButton *)sender
{
if(sender.selected) // Shows the Pause symbol
{
sender.selected = NO;
[self.player pause];
}
else // Shows the Play symbol
{
sender.selected = YES;
[self.player play];
}
}
// MARK: CEPlayerDelegate methods
- (void) player:(CEPlayer *)player didReachPosition:(float)position
{
self.progressView.progress = position;
self.progressSlider.value = position;
}
- (void) playerDidStop:(CEPlayer *)player
{
self.playPauseButton.selected = NO;
self.progressView.progress = 0.0;
self.progressSlider.value = 0.0;
}
#end
where should I make change to get my desired output, help please
Try this, replace otherColor with your 2nd half color. You may have to fix some syntax errors, my version of Xcode wont run on this computer so I couldn't check.
#import "CEViewController.h"
#interface CEViewController ()
{
UIColor *progressColor;
BOOL colorChanged;
}
#end
#implementation CEViewController
#synthesize progressView;
#synthesize progressSlider;
#synthesize playPauseButton;
#synthesize player;
#synthesize progressColor;
#synthesize colorChanged;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.player = [[[CEPlayer alloc] init] autorelease];
self.player.delegate = self;
self.progressColor= [UIColor orangeColor];
[[UISlider appearance] setMinimumTrackTintColor:self.progressColor];
[[CERoundProgressView appearance] setTintColor:self.progressColor];
self.progressView.trackColor = [UIColor colorWithWhite:0.80 alpha:1.0];
self.progressView.startAngle = (3.0*M_PI)/2.0;
colorChanged = false;
}
- (void)viewDidUnload
{
[self setProgressView:nil];
[self setProgressSlider:nil];
[self setPlayPauseButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[progressView release];
[progressSlider release];
self.player = nil;
[playPauseButton release];
[super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)progressSlider:(UISlider *)sender
{
self.player.position = sender.value;
if(sender.value >= 0.5 && colorChanged == false) {
self.progressColor= [UIColor otherColor];
[[UISlider appearance] setMinimumTrackTintColor:self.progressColor];
[[CERoundProgressView appearance] setTintColor:self.progressColor];
colorChanged = true;
}
self.progressView.progress = sender.value;
}
- (IBAction)playPauseButton:(UIButton *)sender
{
if(sender.selected) // Shows the Pause symbol
{
sender.selected = NO;
[self.player pause];
}
else // Shows the Play symbol
{
sender.selected = YES;
[self.player play];
}
}
// MARK: CEPlayerDelegate methods
- (void) player:(CEPlayer *)player didReachPosition:(float)position
{
self.progressView.progress = position;
self.progressSlider.value = position;
}
- (void) playerDidStop:(CEPlayer *)player
{
self.playPauseButton.selected = NO;
self.progressView.progress = 0.0;
self.progressSlider.value = 0.0;
}
#end

iPhone Objective C - can't display new view

I'm finding it difficult to get started in Objective-C.
I'm executing the following code when a button is clicked:
NSLog(#"hi");
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
I can see "hi" in the console when I hit the button, it's just that the view should change to MainMenuDriver. But nothing happens!
Please help!
As per request for more code:
MainMenuDriver.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MainMenuDriver : UIViewController <UINavigationControllerDelegate,CLLocationManagerDelegate>{
IBOutlet UIButton *photos;
IBOutlet UIButton *profile;
IBOutlet UISwitch *onOffline;
IBOutlet UILabel *label1;
NSTimer *uploadGPS_timer;
CLLocationManager *lm;
NSString *lat;
NSString *lng;
}
#property(nonatomic,retain) UIButton *photos;
#property(nonatomic,retain) UIButton *profile;
#property(nonatomic,retain) UISwitch *onOffline;
#property(nonatomic,retain) UILabel *label1;
#property (nonatomic,retain) NSTimer *uploadGPS_timer;
#property(nonatomic,retain) NSString *lat,*lng;
-(IBAction)showMessages:(id)sender;
-(IBAction)showFriends:(id)sender;
-(IBAction)showPhotos:(id)sender;
-(IBAction)showProfile:(id)sender;
-(IBAction)switchSwitched:(id)sender;
-(void)uploadGPS_tick:(NSTimer*)timer;
#end
MainMenuDriver.m
#import "MainMenuDriver.h"
#import "ASIFormDataRequest.h"
#import "JoeMaxiViewController.h"
#import "Photos.h"
#import "Profile.h"
#implementation MainMenuDriver
#synthesize messages,profile,photos,friends,label1;
#synthesize onOffline;
#synthesize uploadGPS_timer;
#synthesize lat,lng;
-(IBAction)showPhotos:(id)sender{
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:nil]];
Photos *x= [[Photos alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:x animated:YES];
}
-(IBAction)showProfile:(id)sender{
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:nil]];
Profile *x= [[Profile alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:x animated:YES];
}
-(void)logout:(id)sender{
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
[lm release];
//[uploadGPS_timer release];
[self.navigationController popViewControllerAnimated:NO];
/*NSString *urlStr=[[NSString alloc] initWithFormat:#"http://www.prestocab.com/driver/ajax/logout.php"];
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response=[request responseString];
NSLog(#"%#",response);
}];
[request setFailedBlock:^{
}];
[request startAsynchronous];*/
}
-(IBAction)switchSwitched:(id)sender{
if(onOffline.on){
[label1 setText:#"For Hire"];
[label1 setTextColor:[UIColor colorWithRed:0.0 green:0.8 blue:0.0 alpha:1.0]];
uploadGPS_timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(uploadGPS_tick:) userInfo:nil repeats:YES];
[self uploadGPS_tick:nil];
}else{
[label1 setText:#"Engaged"];
[label1 setTextColor:[UIColor colorWithRed:0.8 green:0.0 blue:0.0 alpha:1.0]];
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
}
}
-(void)uploadGPS_tick:(NSTimer*)timer{
if(!lat || !lng){
//do nothing
}else{
NSString *urlStr=[[NSString alloc] initWithFormat:#"http://www.prestocab.com/driver/ajax/updateCoords.php"];
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc ]initWithURL:url];
[request setPostValue:lat forKey:#"lat"];
[request setPostValue:lng forKey:#"lng"];
NSLog(#"EOH: %#",lat);
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response=[request responseString];
NSLog(#"%#",response);
//do nothing
}];
[request setFailedBlock:^{
//NSError *error =[request error];
//do nothing
}];
[request startAsynchronous];
}
}
-(void)locationManager:(CLLocationManager*) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation*) oldLocation{
lat=[[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.latitude];
lng=[[NSString alloc]initWithFormat:#"%g",newLocation.coordinate.longitude];
NSLog(#"%#,%#",lat,lng);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.navigationItem.title=#"PrestoCab";
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Logout" style:UIBarButtonItemStylePlain target:self action:#selector(logout:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];
//GPS
lm=[[CLLocationManager alloc] init];
if([CLLocationManager locationServicesEnabled]){
lm.delegate=self;
lm.desiredAccuracy=kCLLocationAccuracyBest;
lm.distanceFilter=30.0f;
[lm startUpdatingLocation];
}
//[self check4messages_tick:nil]; //want to start immediately, not in 10/40 seconds' time
[self uploadGPS_tick:nil];
//check4messages_timer=[NSTimer scheduledTimerWithTimeInterval:40.0 target:self selector:#selector(check4messages_tick:) userInfo:nil repeats:YES];
uploadGPS_timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(uploadGPS_tick:) userInfo:nil repeats:YES];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
if([uploadGPS_timer isValid]){
[uploadGPS_timer invalidate];
}
}
-(void)dealloc{
[super dealloc];
[uploadGPS_timer release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Also, here is
MyClassViewController.h:
#import <UIKit/UIKit.h>
#interface MyClassViewController : UINavigationController{
IBOutlet UIButton *passenger;
IBOutlet UIButton *driver;
}
#property (nonatomic,retain) UIButton *passenger;
#property (nonatomic,retain) UIButton *driver;
-(IBAction) passengerClicked:(id)sender;
-(IBAction) driverClicked:(id)sender;
#end
and MyClassViewController.m:
#import "MyClassViewController.h"
#import "MainMenuDriver.h"
#implementation MyClassViewController
#synthesize passenger;
#synthesize driver;
-(IBAction)passengerClicked:(id)sender{
NSLog(#"passenger");
}
-(IBAction)driverClicked:(id)sender{
NSLog(#"driver");
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (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 (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
I can see a couple of things:
Your nib file's name is different from the name of your class. If you put nil, the UIViewController will try to load a nib file with the UIViewController's name. Your UIViewController can be MainMenuDriver but your nib file name can be MainMenuDriverNibFileName.nib
[self navigationController] is nil.
For this, do the following:
NSLog(#"hi");
if([self navigationController]){
MainMenuDriver *mainMenuDriver= [[MainMenuDriver alloc] initWithNibName:nil bundle:nil];
[[self navigationController]pushViewController:mainMenuDriver animated:YES];
}
else{
NSLog(#"Houston we have a problem");
}
Update 1:
So, its nil, what you can do is the following:
Quick and Dirty:
[self presentViewController:mainMenuDriver animated:YES];
Instead of UIViewController switch to a UINavigationController.

Controls in a ViewController losing their state after memory warning while off screen

The situation is very similar to that described by this my other question, except that the delegation seems to work fine. I'm providing some more detail about my code. I'm just striping out non-relevant/trivial parts.
ReportScreen.h
#interface ReportScreen : UIViewController <UIImagePickerControllerDelegate, UITextViewDelegate, MBProgressHUDDelegate, SoapDelegate, MapLocationChoiceDelegate>
// ...
#property (nonatomic, retain) MKPointAnnotation *annotation;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#property (nonatomic, retain) IBOutlet UIButton *cameraButton;
#property (nonatomic, retain) IBOutlet UIButton *libraryButton;
#property (nonatomic, retain) IBOutlet UIButton *locationButton;
#property (nonatomic, retain) IBOutlet UIButton *sendButton;
#end
ReportScreen.m
#implementation ReportScreen
#synthesize annotation;
#synthesize textView;
#synthesize cameraButton;
#synthesize libraryButton;
#synthesize locationButton;
#synthesize sendButton;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Here I used to store the VC's state to a file but it shouldn't be needed now that I'm assigning it as delegate and said delegate seems to still be there even after a memory warning.
}
- (void)viewDidLoad {
[super viewDidLoad];
placeholderText = #"Tell us what's wrong…";
textView.text = placeholderText;
self.annotation = nil;
[self isReadyToSubmit];
hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:hud];
hud.delegate = self;
hud.labelText = #"Invio in corso…";
hud.dimBackground = YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Here I used to restore the state of the VC from file but… y'know.
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self isReadyToSubmit];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:#"goToMap"]) {
MapScreen *vc = (MapScreen *)segue.destinationViewController;
// HERE's the magic
vc.mapLocationChoiceDelegate = self;
// MAGIC ends
if(self.annotation != nil) {
vc.annotations = [[NSMutableArray alloc] init];
[vc.annotations addObject:self.annotation];
}
}
}
- (BOOL)isReadyToSubmit {
if(self.annotation != nil) {
locationButton.highlighted = YES;
}
if(![textView.text isEqualToString:placeholderText] && self.annotation != nil) {
[sendButton setEnabled:YES];
} else {
[sendButton setEnabled:NO];
}
return [sendButton isEnabled];
}
- (void)textViewDidBeginEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:placeholderText]) {
theTextView.text = #"";
}
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(didFinishEditing:)];
[self.navigationItem setRightBarButtonItem:done animated:YES];
}
- (void)textViewDidEndEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:#""]) {
theTextView.text = placeholderText;
}
[self isReadyToSubmit];
}
- (void)didFinishEditing:(id)sender {
[self.navigationItem setRightBarButtonItem:nil animated:YES];
[self.textView resignFirstResponder];
}
// THIS is my delegate protocol's method
- (void)locationChosen:(MKPointAnnotation *)theAnnotation {
self.annotation = theAnnotation;
NSLog(#"R: %#", textView.text);
}
#end
MapScreen.h
#protocol MapLocationChoiceDelegate <NSObject>
- (void)locationChosen:(MKPointAnnotation *)annotation;
#end
// ---
#interface MapScreen : UIViewController <MKMapViewDelegate>
- (void)handleLongPress:(id)sender;
#property (nonatomic, retain) NSMutableArray *annotations;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property (weak) id<MapLocationChoiceDelegate> mapLocationChoiceDelegate;
#end
MapScreen.m
#implementation MapScreen
#synthesize annotations;
#synthesize mapView;
#synthesize mapLocationChoiceDelegate;
- (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)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;
[self.mapView addGestureRecognizer:lpgr];
[mapView addAnnotations:self.annotations];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#pragma mark - Map handling
- (void)handleLongPress:(id)sender {
if(![sender isKindOfClass:[UILongPressGestureRecognizer class]]) {
return;
}
UILongPressGestureRecognizer *gr = (UILongPressGestureRecognizer *)sender;
if (gr.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [gr locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = touchMapCoordinate;
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
for(id a in self.annotations) {
if(![a isKindOfClass:[MKUserLocation class]]) {
[mapView removeAnnotation:a];
}
}
[mapView addAnnotation:annotation];
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
// NSDictionary *userInfo = [NSDictionary dictionaryWithObject:annotation forKey:#"annotation"];
// [[NSNotificationCenter defaultCenter] postNotificationName:#"PositionChosen" object:nil userInfo:userInfo];
[self.mapLocationChoiceDelegate locationChosen:annotation];
NSLog(#"M: %#", ((ReportScreen *)self.mapLocationChoiceDelegate).textView.text);
}
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
if([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString *AnnotationIdentifier = #"Annotation";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (!pinView) {
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
} else {
pinView.annotation = annotation;
}
return pinView;
}
#end
The issue is:
ReportScreen pushes (performs segue to, actually) the MapScreen.
If I have some data in the UITextView or if I set some state to the buttons in the ReportScreen and I get a memory warning while the MapScreen is pushed, once I go back to the ReportScreen, all those fields don't show those settings. Apparently textView.text is still set, and so are the states of the buttons, they're just not shown.
Question: why?

UIWebView - Trouble displaying current URL in text field

I'm having problems getting the current URL through a URL request and passing it on to the text field above my web view. I tried logging it and it returns NULL, and the text field remains blank.
This is the delegate I added to my implementation file:
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
And here is my WebViewController.h file:
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController {
IBOutlet UIWebView *_webView;
IBOutlet UITextField *_webAddress;
IBOutlet UIActivityIndicatorView *activityIndicator;
NSTimer *timer;
NSString *_webURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) IBOutlet UITextField *webAddress;
#property (nonatomic, retain) NSString *webURL;
- (IBAction) doneButton:(id)sender;
#end
And here is my WebViewController.m file:
#import "WebViewController.h"
#implementation WebViewController
#synthesize webView = _webView;
#synthesize webAddress = _webAddress;
#synthesize webURL = _webURL;
// Dismiss WebViewController
- (IBAction) doneButton:(id)sender {
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
- (void)viewDidLoad
{
[_webView addSubview:activityIndicator];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_webURL]]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:#selector(loading) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)loading {
if (!_webView.loading)
[activityIndicator stopAnimating];
else
[activityIndicator startAnimating];
}
- (void)viewDidUnload
{
_webURL = nil;
_webView = nil;
_webAddress = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc
{
[_webURL release];
[_webView release];
[_webAddress release];
[super dealloc];
}
#end
Does anybody know what I am doing wrong here? Thank you.
Use the - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType delegate instead. This will give you the actual request.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40006951-CH3-SW6
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
_webAddress.text = [url absoluteString];
}

Adding a 3rd button and have date picker for time

NEW CODE
DatePickerViewController.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewControllerDelegate;
#interface DatePickerViewController : UIViewController {
IBOutlet UIDatePicker *datePicker;
id<DatePickerViewControllerDelegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker;
#property (assign) id<DatePickerViewControllerDelegate> delegate;
NSInteger buttonPressed;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed:(id)sender;
#end
#protocol DatePickerViewControllerDelegate <NSObject>
#optional
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController.m
#import "DatePickerViewController.h"
#implementation DatePickerViewController
#synthesize datePicker, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker date]];
[self.delegate datePickerViewController:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker release];
[super dealloc];
}
#end
DatePickerViewController2.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewController2Delegate;
#interface DatePickerViewController2 : UIViewController {
IBOutlet UIDatePicker *datePicker2;
id<DatePickerViewController2Delegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker2;
#property (assign) id<DatePickerViewController2Delegate> delegate;
NSInteger buttonPressed2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed2:(id)sender;
#end
#protocol DatePickerViewController2Delegate <NSObject>
#optional
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController2.m
#import "DatePickerViewController2.h"
#implementation DatePickerViewController2
#synthesize datePicker2, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker2";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker2. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker2.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed2:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController2:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker2 date]];
[self.delegate datePickerViewController2:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker2 release];
[super dealloc];
}
#end
DatePickerModalExampleAppDelegate.h
#import <UIKit/UIKit.h>
#class DatePickerModalExampleViewController;
#interface DatePickerModalExampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
DatePickerModalExampleViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet DatePickerModalExampleViewController *viewController;
#end
DatePickerModalExampleAppDelegate.m
#import "DatePickerModalExampleAppDelegate.h"
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
DatePickerModalExampleViewController.h
#import <UIKit/UIKit.h>
#import "DatePickerViewController.h"
#import "DatePickerViewController2.h"
#interface DatePickerModalExampleViewController : UIViewController <DatePickerViewControllerDelegate> {
IBOutlet UIButton *button;
IBOutlet UIButton *button2;
IBOutlet UIButton *button3;
}
#property(nonatomic, retain) IBOutlet UIButton *button;
#property(nonatomic, retain) IBOutlet UIButton *button2;
#property(nonatomic, retain) IBOutlet UIButton *button3;
-(IBAction)buttonPressed:(id)sender;
-(IBAction)buttonPressed2:(id)sender;
#end
DatePickerModalExampleViewController.m
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleViewController
#synthesize button;
#synthesize button2;
#synthesize button3;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (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];
}
*/
-(IBAction)buttonPressed:(id)sender{
NSLog(#"I was pressed");
buttonPressed = ((UIButton *)sender).tag;
DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
switch (((UIButton*)sender).tag)
{
case 100001:
NSLog(#"Button 1 was pressed");
//some code
break;
case 100002:
NSLog(#"Button 2 was pressed");
//some code
break;
}
}
-(IBAction)buttonPressed2:(id)sender{
NSLog(#"I was pressed2");
buttonPressed2 = ((UIButton *)sender).tag;
DatePickerViewController2 *datePickerViewController2 = [[DatePickerViewController2 alloc] initWithNibName:#"DatePickerViewController2" bundle:nil];
datePickerViewController2.delegate = self;
[self presentModalViewController:datePickerViewController2 animated:YES];
[datePickerViewController2 release];
switch (((UIButton*)sender).tag)
{
case 100003:
NSLog(#"Button 3 was pressed");
//some code
break;
}
}
-(void)viewDidLoad{
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
self.button3.tag = 100003;
buttonPressed = -1;
buttonPressed2 = -1;
}
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed];
buttonPressed = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed2 == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed2];
buttonPressed2 = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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 {
[button3 release];
[button2 release];
[button release];
[super dealloc];
}
#end
Hello you can set the property "tag" on button to identify it
Uncomment
- (void)viewDidLoad {
[super viewDidLoad];
}
And type :
- (void)viewDidLoad {
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
}
then
turn in DatePickerModalExampleViewController.h
(IBAction)buttonPressed to (IBAction)buttonPressed:(id)sender;
Then turn in DatePickerModalExampleViewController.m
-(IBAction)buttonPressed to -(IBAction)buttonPressed:(id)sender
and in DatePickerModalExampleViewController.m this method could be like that :
-(IBAction)buttonPressed:(id)sender
{
switch(((UIButton*)sender).tag)
{
case 100001
NSLog(#"Button 1 was pressed");
DatePickerViewController *datePickerViewController =[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
break;
case 100002 :
NSLog(#"Button 2 was pressed");
// some code
break;
}
}
As you use the interfacebuilder I'm not friend with it but you must relink your actions
I'm writting from my PC so without xcode some code can contains syntax error be carreful. but it's the main idea.
Use tag for both buttons and check the condition accordingly...