load/refresh button in my custom web browser - objective-c

So I'm building a custom web browser with a a lot of custom features, but I'm having a problem with something very simple. I have a NSTimer:
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(checkLoad) userInfo:nil repeats:YES];
and here is the method it calls:
-(void)checkLoad{
if (webView.loading) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//add button to address bar
UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
stopButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[stopButton addTarget:self action:#selector(stop) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = stopButton;
addressBar.rightViewMode = UITextFieldViewModeUnlessEditing;
}
else if (!(webView.loading)) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//add button to address bar
UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
refreshButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
[refreshButton addTarget:self action:#selector(refresh) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = refreshButton;
addressBar.rightViewMode = UITextFieldViewModeUnlessEditing;
}
}
the buttons show up just fine, and they change when the page is loading or not loading. but the interaction with them is very spastic. the refresh button works most of the time, but the stop button almost never works. I've played with the timing on the NSTimer making it longer and shorter to no avail.
also, I know the button images are wrong, but those are just placeholder's until I can get the refresh and stop loading images like the ones in safari.
any ideas? I am totally willing to do something completely different to detect when the page is loading (that would actually be preferred as I don't want an NSTimer looping every .2 seconds if I can avoid it but this was the only way I could find.

What's wrong with using the delegate methods of UIWebView? See UIWebViewDelegate.
Setting up timers that fire every small fraction of a second so you can check something is a 'code smell'.

Related

Xcode Animations complete instantly - CAAnimations call didStop - flag = FALSE

I'm getting some weird bugs. I thought I had a handle on this. I copied code from one of my other projects. I'm wondering if it could be something to do with my custom class.
I have a view controller initialize my custom class called "TitleCardView"
Inside there I have a bunch of animations like this one:
CGPoint startPointb = borderMaskLayer.position;
CGPoint endPointb = CGPointMake(borderMaskLayer.position.x, borderMaskLayer.position.y-1000);
CABasicAnimation* bmoveAnim = [CABasicAnimation animationWithKeyPath:#"position"];
bmoveAnim.delegate=self;
[bmoveAnim setValue:#"borderMaskAnim1" forKey:#"id"];
bmoveAnim.fromValue = [NSValue valueWithCGPoint:startPointb];
bmoveAnim.toValue = [NSValue valueWithCGPoint:endPointb];
bmoveAnim.duration = 1;
[bmoveAnim setBeginTime:CACurrentMediaTime()+.4];
bmoveAnim.fillMode = kCAFillModeForwards;
bmoveAnim.removedOnCompletion = NO;
bmoveAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[self.borderLayer.mask addAnimation:bmoveAnim forKey:#"position"];
[self.borderWhiteLayer.mask addAnimation:bmoveAnim forKey:#"position"];
The animation works fine but when I try to implement AnimationDidStop{, as soon as the view loads, all the animations get logged by the delegate method with the FALSE (did not finish) flag.
I added a button and tried to use:
[UIView animateWithDuration:6 animations:^{
continueButton.alpha = 1.0f;
}];
and this code with the delay parameter....
Same problem. As soon as the view loads, its like the animation gets run immediately with a duration of 0.
Are you not supposed to add animations in your init method? I feel like there must be a rule I'm breaking that I don't know about.
This code does work:
this button is the last thing in the init method
continueButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[continueButton addTarget:self
action:#selector(titleNext)
forControlEvents:UIControlEventTouchUpInside];
[continueButton setTitle:#"Click to Continue" forState:UIControlStateNormal];
continueButton.frame = CGRectMake(0.0, 390.0, 320.0, 75.0);
[self addSubview:continueButton];
continueButton.alpha = 1.0;
then this is the method it calls
-(void)titleNext{
// proceeds to the motto page from the title page
[UIView animateWithDuration:.6 animations:^{
continueButton.alpha = 0.0f;
}];
}
So can anyone tell me why my animations are acting weird???
I recreated the project and found the animationDidStop delegate worked when the animations were created in -(void)viewDidAppear{ instead of -(void)viewDidLoad{
For swift it works if the animations are in
override func viewDidAppear(_ animated: Bool)

Creating control pad

I am trying to code a controller for an image view to move using buttons.
inside up button code :
-(IBAction)upButton:(id)sender{
mainChac.center = CGPointMake(mainChac.center.x, mainChac.center.y - 5);
}
code is working properly but I have to tap it repeatedly to keep moving up, I wanna know which method to call, to move it, while holding the up button.
edit :
-(void)touchDownRepeat{
mainChac.center = CGPointMake(mainChac.center.x, mainChac.center.y - 5);
}
-(IBAction)upButton:(id)sender{
[upButton addTarget:self action:#selector(touchDownRepeat) forControlEvents:UIControlEventTouchDownRepeat];
}
edit 2: solution
-(void)moveUp{
mainChac.center = CGPointMake(mainChac.center.x, mainChac.center.y - 5);
}
- (void)holdDown
{
NSLog(#"hold Down");
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moveUp) userInfo:nil repeats:YES];
}
- (void)holdRelease
{
NSLog(#"hold release");
[timer invalidate];
}
-(IBAction)upButton:(id)sender{
[upButton addTarget:self action:#selector(holdDown) forControlEvents:UIControlEventTouchDown];
[upButton addTarget:self action:#selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];
}
EDIT:
What you need to to have 2 events, one for while the button is pressed down and another for when the button is released like so:
[aButton addTarget:self action:#selector(holdDown) forControlEvents:UIControlEventTouchDown];
[aButton addTarget:self action:#selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];
- (void)holdDown
{
NSLog(#"hold Down");
}
- (void)holdRelease
{
NSLog(#"hold release");
}
Have your hold down function start a loop, and your holdRelease stop the loop.
EDIT-2:
An easy way (but perhaps not the best way) to achieve this loop would be to use NSTImer scheduledTimerWithTimeInterval inside the hold down and invalidate it in the release method.
all of this stuff has been done before, please try googling this stuff. Here is a stackoverlfow question with an example: ios scheduledTimerWithTimeInterval for amount of time

Press and hold to make Image move

I have a button and an image. When the button is pressed and held I want the image to movie across the screen quickly. Right now after I press and hold it just moves after I let go. I need it to start moving after a certain amount of time and stop when I let go.
here is what I have:
- (IBAction)buttonDown:(id)sender
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
x = x + 100;
}
With below code, you have to push 3 seconds to move _imageView, and then the image begins moving, and when you release the button, the image stops.
- (IBAction)pushToMove:(id)sender {
[self performSelector:#selector(move) withObject:nil afterDelay:3.0];
}
- (void)move
{
_nt = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(goRight)
userInfo:nil
repeats:YES];
}
- (void)goRight
{
_imageView.frame = CGRectMake(_imageView.frame.origin.x + 10, _imageView.frame.origin.y,
_imageView.frame.size.width, _imageView.frame.size.height);
}
- (IBAction)stop
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(move) object:nil];
[_nt invalidate];
}
I put this sample project to GitHub. You can download and just run it.
https://github.com/weed/p120804_ImageMoveDuringPushButton
This can be done in interface builder by simply liking to the buttons touch down property instead of touch up inside. In code it looks like this:
[myButton addTarget:self action:#selector(myMethod) forControlEvents:UIControlEventTouchDown];
In addition to this, you'll want to do some state checking on your animation, and use UIViewAnimationOptionBeginFromCurrentState as an option to help it pick up where it left off when the user presses the button again.

How to use UIActivityIndicatorView on custom UIButton?

I want to use UIActivityIndicatorView on my custom UIButton.
Here is my code:
if (sender.tag == 1)
{
// Start animating
activityIndicator.hidden = NO;
[activityIndicator startAnimating];
// Check if the network is available
if ([self reachable]) {
// Stop animating
activityIndicator.hidden = YES;
[activityIndicator stopAnimating];
}
}
What I want to do here is:
Once the user touch the button, I want to start the ActivityIndicatior while Reachable checking the network availability. Once it done pass it to the next view.
Update
UIActivityIndicator is on top of my custom UIButton. It build successfully, but ActivityIndicator is not showing when I touch the button.
I'm sure you had your answer since then.
After 4 years, language has changed to Swift, but I had the same problem : UIActivityIndicatorView is not showing when I add it through :
self.myButton.addSubview(self.myIndicatorView)
I had to climb a level up :
self.myButton.superview!.addSubview(self.myIndicatorView)
Assuming everything else is correct in your project, the problem here is that you're showing and hiding an activity indicator in the same event loop, without giving a pause to draw it. Let me explain:
If you have the code:
UIView* view = someView;
view.backgroundColor = [UIColor redColor];
// various synchronous operations
view.backgroundColor = [UIColor yellowColor];
The view will only ever have a background color of yellow.
To answer your question, you probably want to animate the spinner, do some asynchronous operation, then stop the animation. The key being to not stall on the main event loop while your asynchronous task is running. If your comfortable with blocks it would look something like this:
if (sender.tag == 1) {
// Start animating
activityIndicator.hidden = NO;
[activityIndicator startAnimating];
// Check if the network is available
[self checkReachableWithCallback:^{
// Stop animating
activityIndicator.hidden = YES;
[activityIndicator stopAnimating];
}];
}

How to flash a button on UI thread?

I have a button on my UI that I would like to flash (turn on and then off again) every 800ms, once the button has been pressed. I do that with the following code:
- (void)flickEmergencyButton {
// Check whether an emergency is in progress...
if (model.emergencyInProgress) {
// ...and if so, flick the state
self.emergencyButton.selected = !self.emergencyButton.selected;
// Make this method be called again in 800ms
[self performSelector:#selector(flickEmergencyButton) withObject:nil afterDelay:0.8];
} else {
// ...otherwise, turn the button off
self.emergencyButton.selected = NO;
}
}
...which works really well, except: There is a UIScrollView on the UI as well and while the user has his finger down on it and is scrolling around, the button freezes. While I completely understand why that is, I am not sure what to do about it.
The performSelector:withObject:afterDelay message schedules the message to be send on the current thread, which is the main thread, ie. the UI tread and hence does not get to process the message until all other UI activity has come to an end. Correct? But I need to do this on the UI thread as I cannot select/un-select the button on any other thread, right? So what is the solution here?
I would recommend using Core Animation. Try something like this:
-(void) flash{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
if( emergency ){
// Start flashing
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:YES];
[btn setAlpha:0.0f];
}else{
// Stop flashing
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationRepeatCount:1];
[btn setAlpha:1.0f];
}
emergency = !emergency;
[UIView commitAnimations];
}
Where btn is declared as
#property(nonatomic, retain) IBOutlet UIButton *btn;
and emergency is a simple BOOL variable.
Call flash to start and to stop the animation.
In this example we animate the alpha attribute for simplicity, but you can do the same with the button backcolor, as Sam said in his answer, or whatever attribute you like.
Hope it helps.
UPDATE:
Regarding making the transition between two images, try calling imageFlash instead of flash:
-(void) imageFlash{
CABasicAnimation *imageAnimation = [CABasicAnimation animationWithKeyPath:#"contents"];
[btn setImage:normalState forState:UIControlStateNormal];
if( emergency ){
imageAnimation.duration = 0.5f;
imageAnimation.repeatCount = 1000;
}else{
imageAnimation.repeatCount = 1;
}
imageAnimation.fromValue = (id)normalState.CGImage;
imageAnimation.toValue = (id)emergencyState.CGImage;
[btn.imageView.layer addAnimation:imageAnimation forKey:#"animateContents"];
[btn setImage:normalState forState:UIControlStateNormal]; // Depending on what image you want after the animation.
emergency = !emergency;
}
Where normalState and emergencyState are the images you want to use:
Declared as:
UIImage *normalState;
UIImage *emergencyState;
Assigning the images:
normalState = [UIImage imageNamed:#"normal.png"];
emergencyState = [UIImage imageNamed:#"alert.png"];
Good luck!
While this feels like a job for CoreAnimation (perhaps animating the backgroundColor of a custom UIControl) you could accomplish this with an NSTimer running in the appropriate run loop mode.
e.x.
NSTimer *timer = [NSTimer timerWithTimeInterval:0.8f target:self selector:#selector(flicker:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
and when you want to stop animation:
[timer invalidate], timer = nil;
button.selected = NO;
By adding the timer to all NSRunLoopCommonModes, you not only add it to the default run loop mode but the mode it is in while user interaction is being continuously processed (UITrackingRunLoopMode.)
Apple's docs give a more thorough explanation of run loop modes and run loops in general.