switching from view 1 to view 2 without pressing any buttons - iphone

How to switch from view1 to view 2 without having any button pressed. In my views i have is uiimageview and uitextview
With the NSTimer i m trying to do this
in the viewdidload method by using the following code:
In the firstviewcontroller.h file
#interface FirstViewController : UIViewController
{
NSTimer *SwitchingTimer;
}
In the firstviewcontroller.m file
- (void)viewDidLoad
{
[super viewDidLoad];
SwitchingTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(SwitchView) userInfo:nil repeats:YES];
}
-(void)SwitchViews:(id)sender
In the secondviewcontroller.m file
-(void) SwitchView
{
SecondViewController *SecondView = [[SecondViewController alloc]
initWithNibName:#"SecondViewController" bundle:nil];
SecondView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:SecondView animated:YES];
[SwitchingTimer invalidate];
self.SwitchingTimer = nil;
}
but nothing is happening. Can someone please tell me what i m missing in my code. Will appreciate help.
Thanks in advance.

There are a few issues in your code that are worth mentioning though I am not sure if those will provide you a solution.
Why do you want to repeat the timer every 2 seconds. I think you just want to switch to next view only once and if so then dont repeat the timer. So no need to invalidate the timer.
Your code for the SwitchView method is leaking memory. Please make sure that the SecondView is released after presenting the modal view(in case you are not using ARC).
Please follow the standard naming conventions. For eg: methods and variables should start with lowercase.
Regarding your issue please make sure that the nib name is correct and you are getting a valid object for the second view controller. You can check by using NSLog. Also ensure that the method Switchview is called. Try putting a break point and verify that it is called.
Another Option
If you just want to switch the view only once you can go for another option which does not make use of the NSTimer. For this, you can use performSelector:withObject:afterDelay:. This is just another option for the scenario I mentioned above.

You need to add it to the run loop:
- (void)viewDidLoad
{
[super viewDidLoad];
SwitchingTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(SwitchView) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer: SwitchingTimer forMode:NSDefaultRunLoopMode];
}
Also, you could rename -(void)SwitchView to -(void)switchViewTimerDidFire:(NSTimer *)timer. From the Documentation:
[...] The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
The timer passes itself as the argument to this method.

Related

How to call one view controller to another view controller After 1000 millisecond in Iphone [duplicate]

This question already has answers here:
How does -performSelector:withObject:afterDelay: work?
(2 answers)
Closed 9 years ago.
I'm new to iPhone development and I'm running iOS 6.1. I have two View Controllers called firstViewController and secondViewController. I need to call one view controller from another view controller after 1000 milliseconds without any click of a button, imageView etc.
How is it possible?
You can use the code like this
NSTimer *timer;
timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(touchDetected) userInfo:nil repeats:NO];// because 1000 miliseconds=10 sec
In the touchDetected Method put your code
-(void)touchDetected
{
LoginPage * loginPageObj=[[LoginPage alloc]initWithNibName:#"LoginPage" bundle:nil];
[self.navigationController pushViewController:loginPageObj animated:YES];
[timer invalidate];
}
Here you can use code according to you like change the method name and ViewControllers name.
Hope this helps.
you can use this method
[self performSelector:#selector(methodToCall:) withObject:nil afterDelay:1000.0];
try with
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(pushView) userInfo:nil repeats:NO];
-(void)pushView {
SeconViewController *SeconViewControllerObj=[[SeconViewController alloc] initWithNibName:#"SeconViewController" bundle:nil];
[self.navigationController pushViewController:SeconViewControllerObj animated:YES];
}
You can call a Selector (Method) using NSTimer after a certain time using this -
[NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(id)#> selector:<#(SEL)#> userInfo:<#(id)#> repeats:<#(BOOL)#>];
what you need is a methode, lets call it
-(void)pushNextVC;
and the call
[self performSelector:#selector(pushNextVC) withObject:nil afterDelay:<#(NSTimeInterval)#>];
also possible are solutions with NSTimer, but for this the "performSelector" is enought :)
You can make use of
[self performSelector:#selector(gotoNextView) withObject:nil afterDelay:]

NSTimer in Objective C when Click on Home Button

I have NSTimer in ViewController Class.. And all the methods for NStimer are in that class.. My NSTimer is working properly for play and pause... When i press home button on iPhone also the timer is working properly(it starts running from the time where the application enters into background when the application enters into foreground)... In my application i am rising an alert quickly when my application enters into foreground(UIAlertview in application didEnterForeGround). Here my NSTimer is running when the alert is on the screen(didn't give response to alert).. I want stop the NSTimer Upto the User responding to my alert... After that I want to start the NSTimer... How Can i do that...? Please help me... Thanks in Advance... I want call the NSTimer methods from Appdelegate.m file... Iam calling these methods properly... And the methods in ViewController are called.. But the action is Not Performing... For the Same method when call from viewController class it is working...
enter code here
ViewController.h
+(ExamViewController *)evcInstance;
ViewController.m
ExamViewController *evc = nil;
#implementation ExamViewController
+(ExamViewController *)evcInstance
{
if(!evc)
{
evc = [[ExamViewController alloc] init];
}
return evc;
}
- (void)onStartPressed
{
stopwatchtimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:stopwatchtimer forMode:NSRunLoopCommonModes];
resume.hidden = YES;
resume.enabled=NO;
pause.hidden = NO;
pause.enabled=YES;
}
- (void)onStopPressed
{
[stopwatchtimer invalidate];
stopwatchtimer = nil;
pause.hidden = YES;
pause.enabled=NO;
resume.hidden = NO;
resume.enabled=YES;
}
Appdelegate.m
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[ExamViewController evcInstance] onStopPressed];
NSLog(#"applicationWillEnterForeground");
if(viewCalled ==YES)
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:#"" message:#"DO! You Want To continue" delegate:self cancelButtonTitle:#"YES" otherButtonTitles:#"NO", nil];
[alertview show];
[alertview release];
}
/*
Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
*/
}
a few things:
1) It looks like an incomplete singleton design. If you really want a singleton, refer to a post like this one.
2) No need to add stopwatchtimer to the current run loop. The scheduledTimerWithTimeInterval method schedules it for you.
3) I don't see where you declare stopwatch timer, but be sure to declare it as a retained property (or strong in ARC).
4) To stop the timer, just call [stopwatchtimer invalidate]; To restart it, re-instantiate and overwrite the old one using the same scheduledTimerWithTimeInterval class method that you called originally.
5) To do anything when an alert view completes, implement the delegate method:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
So you can invalidate the timer before presenting the alert, then rebuild it when you get notified the alert is finished.

To which source file does NSRunLoop/NSTimer belong?

I've been trying to figure out how to setup an NSTimer to allow me to print the current time in a UILabel within a View, and have it update every second (no finer resolution required - just a simple clock).
At first, I wasn't using a NSRunLoop, but if I try and include one, the execution just "spins" inside the loop, blocking further execution. I have posted my code below.
-(id) printCurrentTime {
now = [NSDate date];
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeStyle:NSDateFormatterMediumStyle];
NSString *nowstr = [dateFormat stringFromDate:now];
[dateFormat release];
NSLog(#"Current time is: %#",nowstr);
return nowstr;
}
And in the ViewController source file, I execute as per:
TimeStuff *T = [[TimeStuff alloc] init];
NSString *thetime = [T printCurrentTime];
[timelabel setText:thetime];
[T release];
[self.view addSubview:timelabel];
NSTimer *timmeh = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(printCurrentTime) userInfo:nil repeats:YES];
[[[NSRunLoop currentRunLoop] addTimer:timmeh forMode:NSDefaultRunLoopMode] run];
The "TimeStuff" class is effectively an empty class, save for the printCurrentTime function.
Questions:
1) Should I be including the RunLoop in the AppDelegate class? I am having trouble visualising how this all should hang together, as in - what are the steps to achieving a Loop based on Timer to update a text label with the up-to-second time. Pretty stumped.
2) In the event that I should use a NSThread, should that also be in it's own class / the Delegate class.
3) Is the ViewController class totally out of bounds for looping/timers, and simply the "eye candy" class, with callbacks to functions in the Delegate class?
Thank you for your time and patience.
You don't need to deal with run loops at all.
This line :
NSTimer *timmeh = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(printCurrentTime) userInfo:nil repeats:YES];
will create a timer and attach it to the current thread's run loop for you. You don't need the [NSRunLoop addTimer:forMode:] call at all - you can delete that line.
PS You certainly don't need to go as far as NSThreads!
EDIT Regarding your comment :
You will need to make an instance of your TimeStuff class for the timer to use if that's where your printCurrentTime method is. i.e.
#interface MyViewController : UIViewcontroller {
TimeStuff *timeStuff
}
and in your viewDidLoad method:
- (void)viewDidLoad {
[super viewDidLoad];
...
// Create our timestuff if we don't have one already
if (nil == timeStuff)
timeStuff = [[TimeStuff alloc] init];
// Start the timer
[NSTimer scheduledTimerWithTimeInterval:1.0 target:timeStuff selector:#selector(printCurrentTime) userInfo:nil repeats:YES];
and not forgetting dealloc
- (void)dealloc {
[timeStuff release];
...
[super dealloc];
}
Passing in the timeStuff as the target for the timer tells it where to look for the printCurrentTime method!
Hope that helps,
PS All the line #class TimeStuff does is tell the compiler that there is a class called TimeStuff. It has no idea that you want to use it for your timer's selector!

Change NSTimer speed with variable?

I have a timer that launches in viewDidLoad that looks like this
[NSTimer scheduledTimerWithTimeInterval:0.001f target:self selector:#selector(Dragon:) userInfo:nil repeats:YES];
I want to be able to change my Interval with a variable. However, any time I try to place a variable where the 0.001f is I get errors... any ideas?
I have an app that does exactly what you are asking. I allow the user to change the speed of the timer within the app so I need to make that speed a variable. Here's how I did it:
I create a timer property on my main view controller class.
I initialize the timer when the main view controller class loads.
Each time thereafter, I invalidate my timer and reset it when the value changes.
Some snippets from inside of my main view controller .m file:
//How often to switch views (float)
#define kInterval [[NSUserDefaults standardUserDefaults] integerForKey:#"interval"]
- (void) viewDidAppear:(BOOL)animated{
[self setTimer];
}
- (void) setTimer{
[self.timer invalidate];
[self setTimer: [NSTimer scheduledTimerWithTimeInterval:kInterval target:self selector:#selector(timerFired) userInfo:nil repeats:YES]];
}
Is the app returning from a background process? If so, you may need to re-set the timer. You might also want to peek at CADisplayLink: http://developer.apple.com/library/ios/#documentation/QuartzCore/Reference/CADisplayLink_ClassRef/Reference/Reference.html%23//apple_ref/doc/uid/TP40009031
#King Popsicle you can take help of this method
(void)applicationWillEnterForeground:(UIApplication *)application OR
(void)applicationDidBecomeActive:(UIApplication *)application
You can fix the things in this method regarding the timer values :)

UIImagePickerController not loading in viewDidLoad for iPhone SDK

I'm trying to show a UIImagePickerController as soon as one of my view controller loads. I'd like to this without the user having to press a button so I overrode the viewDidLoad method as follows:
- (void)viewDidLoad {
[super viewDidLoad];
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.allowsImageEditing = YES;
imagePickerController.delegate = self;
[self presentModalViewController:imagePickerController animated:YES];
[imagePickerController release];
}
This compiles and runs, however when the view controller is loaded the image picker is not displayed. This code works fine if I attach it to an event of a button for example. Any ideas?
Thanks.
I had the same problem but solved it. Try using
-(void) awakeFromNib {
}
It will load just after everything else loads.
Try putting the code in
-(void)viewDidAppear
That even runs every time the view appears on the screen though (including when it appears after you dismiss the UIImagePicker), so you might have to add a BOOL value to make it only happen the first time it shows, or when you want it (i.e. not after dismissing a modal view).
It seems that viewDidLoad is too early to use presentModalViewController:animated:. I'd sugget to fork off a one-shot timer to call the method from next run loop iteration:
[NSTimer
scheduledTimerWithTimeInterval:0
target:self
selector:#selector(onLoadTimer:)
userInfo:nil
repeats:NO];
add the following method:
- (void)onLoadTimer:(id)unused
{
[self presentModalViewController:imagePickerController animated:YES];
[imagePickerController release];
}