UIActionSheet taking long time to respond - iphone

I am creating a UIActionSheet on actionSheet:clickedButtonAtIndex delegate method.
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
if(buttonIndex == 1){
[self.myFirstView removeFromSuperview];
if (!self.mySecondView) {
[[NSBundle mainBundle] loadNibNamed:#"MySecondView" owner:self options:nil];
}
[self.mySecondView setFrame:CGRectMake(0, 0, 320, 480)];
[[UIApplication sharedApplication].keyWindow addSubview: self.mySecondView];
UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:#""
delegate:self
cancelButtonTitle: nil
destructiveButtonTitle: deleteContacts
otherButtonTitles: cancel, nil];
action.tag = 102;
[action showInView:self.view];
[action release];
}
I handle the click event of this UIActionSheet in the exact same method as above.
if(actionSheet.tag == 102){
if(buttonIndex == 0){
if([[NSBundle mainBundle] loadNibNamed:#"MyThirdView" owner:self options:nil]) {
[self.myThirdView setFrame:CGRectMake(0, 0, 320, 480)];
[[UIApplication sharedApplication].keyWindow addSubview:self.myThirdView];
}
[self.mySecondView removeFromSuperview];
[self.doneButton.target performSelector:self.doneButton.action withObject:self.doneButton.target];
[self performSelector:#selector(RemoveView) withObject:self afterDelay:3.0];
}
}
The problem I am facing is that, the UIActionSheet takes too much time to respond. When I click on the UIActionSheet button, its in a frozen state for 2 or 3 seconds, before myThirdView loads. I am not able to understand, whats the response delay in this case as the first thing I do in the UIActionSheet button click event method is to load myThirdView. The rest of the code is executed only after the code to load the myThirdView. But even the first line of code seems to execute after a delay.
Any suggestions?

this is perhaps due to this
[self performSelector:#selector(RemoveView) withObject:self afterDelay:3.0];
make an other methods and do this in that method. like this
[self viewRemover];
and in viewRemover
-(void) viewRemover
{
[self performSelector:#selector(RemoveView) withObject:self afterDelay:3.0];
}
so your code will be like this now
if(actionSheet.tag == 102){
if(buttonIndex == 0){
if([[NSBundle mainBundle] loadNibNamed:#"MyThirdView" owner:self options:nil]) {
[self.myThirdView setFrame:CGRectMake(0, 0, 320, 480)];
[[UIApplication sharedApplication].keyWindow addSubview:self.myThirdView];
}
[self.mySecondView removeFromSuperview];
[self.doneButton.target performSelector:self.doneButton.action withObject:self.doneButton.target];
[self performSelectorInBackground:#selector(viewRemover) withObject:nil];
}
}

User interface actions run in the main thread and only occur when your method ends. So, MyThirdView will not appear until the other instructions have finished. The only thing I can figure is delaying that is:
[self.doneButton.target performSelector:self.doneButton.action withObject:self.doneButton.target];
If you are doing any heavy calculation or net conection, for sure that is the reason.
OTOH, I think you'd better modify that line:
[self.doneButton.target performSelector:self.doneButton.action withObject:self.doneButton];
if you want to simulate a button touch action.

Question. Does the UIActionSheet freeze, or does it disappear and the 3rd view isn't visible for 2-3 seconds?
This could be due to 1 of 2 problems.
If the entire action sheet freezes, then you are doing some heavy lifting when you init that 3rd view, you are loading some core data, or a lot of assets, or something that is taking a long time. If this is the case, you'll need to reformat HOW you load that 3rd view. I'd suggest pushing any heavy loading to the background (this means if you have a lot of images in your xib, you may need to load them in code).
The other possibility, is you are adding the 3rd view BELOW the 2nd view, and then not hiding the 2nd view for 3 seconds (done by performing the selector with a delay). If this is the case, simply remove the delay.
I made a couple of classes to help me time executions and find the bottlenecks in my code, it seems like they might help you now.
http://forrst.com/posts/Code_Execution_Timer_for_iOS_Development-dSJ

How big is your third view. if the nib file needs to load too much, you may be waiting for a lot to happen, also if you have to change some UI elements and your blocking the UI thread, you will hault your app until a timeout occurs and the app will shift some things to compensate..
the route I take with this is dispatch_async and dispatch_sync
// This will release the UI thread which may be blocking your calls.
// You can use any of the DISPATCH_QUEUE_PRIORITY_.... values to set how important this block is.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// this command will get added to the stack and return without a hitch.
// the block will be run the next time the main runloop ends.
dispatch_async(dispatch_get_main_queue(), ^{
// do some UI work that can happen without a hitch, and does not impact the calling block
});
// this command will act much the same. but will pause the background execution
// of this block until the runloop has executed this and returned.
dispatch_sync(dispatch_get_main_queue(), ^{
// do some UI work that must be completed to continue.
});
});
doing too much in the UI thread will pause the execution of things that get stacked on the queue. Shipping all code to the background thread and only skipping to the UI thread when you need to alter the UI is a better and more responsive way to code your iphone app.
I hope this helps :)

in Swift 4:
I wrapped the code with this block
DispatchQueue.main.async {
// your code to show action sheet.
}
for example
DispatchQueue.main.async {
let alert = UIAlertController(title: "Options", message: String("What do want to do?"), preferredStyle: UIAlertController.Style.actionSheet)
alert.addAction(UIAlertAction(title: "Open", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
self.myOpen(code: self.codes[indexPath.row])
}))
alert.addAction(UIAlertAction(title: "Delete", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
self.myDelete(indexPath: indexPath)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
print("Cancel")
}))
self.present(alert, animated: true, completion: nil)
}

Related

Having issue updating hud ivar during in-app purchase

I have recently set-up an in-app purchase mechanism in my app. During the purchase i would like to update an hud (i am using the mbprogresshud) according to two kinds of events: i start a purchase and i receive a validation of the purchase. The problem i am facing is that the hud is never updated with the one i want when the purchase is done (custom view):
When i click on the purchase button:
-(IBAction)buyButtonTapped:(id)sender {
self.hud = [[SCLProgressHUD alloc] initWithView:self.view];
[self.view addSubview:self.hud];
self.hud.labelText = #"Connecting...";
self.hud.minSize = CGSizeMake(100 , 100);
[self.hud show:YES];
...
}
When i receive a notification that the purchase was successful:
-(void)productPurchased:(NSNotification *)notification {
self.hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"checkmark_icon.png"]];
self.hud.mode = SCLProgressHUDModeCustomView;
self.hud.labelText = #"Thanks for your purchase!";
...
}
Setting the self.hud.customView property in the last method will trigger a [self setNeedsLayout]; and [self setNeedsDisplay] within the hud class but still i don't observe any change.
Any possible idea of what i am doing wrong here?
As mentioned on the mbprogress hud readme, update of the UI when tasks are performed on the main thread required a slight delay to take effect. What happen in my case is that the hud was a strong property of a popover controller that i dismiss immediately so i didn't get a chance to see the update happening. I now dismiss the controller in the completion block of:
-(void)showAnimated:(BOOL)animated
whileExecutingBlock:(dispatch_block_t)block completionBlock:(void
(^)())completion
And my code snippet look like like this for the dismiss:
[_hud showAnimated:YES whileExecutingBlock:^(void){
[self.successPurchaseSoundEffect play];
_hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"checkmark_icon.png"]];
_hud.mode = SCLProgressHUDModeCustomView;
_hud.labelText = #"Thanks!";
// We need to pause the background thread to let the music play and the hud be updated
sleep(1);}
completionBlock:^(void){
[self.delegate dismissPurchaseInfoController:self];
}];

UIActivityIndicatorView unresponsive

When a UIButton is triggered, a UIActivityIndicator is started, and then stopped when implementLogin finishes:
-(IBAction)loginButton {
NSLog(#"loginButton triggered");
// Checks the Fields are not empty
if ([sessionIdField.text length] != 0 && [usernameField.text length] != 0 ) {
NSLog(#"Beginning Spinner");
// Displays spinner
[activitySpinner startAnimating];
[self implementLogin];
// Displays spinner
[activitySpinner stopAnimating];
}
}
However at runtime, the spinner doesn't appear! I have set the spinner to 'hide when stopped'.
When I set the activity indicator to animate before the view loads, it appears as it should, so I'm guessing it has a problem with the UIButton... (Also, I'm using 'Touch Up Inside' for the button.)
It's a simple problem... Can anyone help?
Thanks
Whatever implementLogin is doing (making a network request, perhaps?), it's doing it on the main thread, which is likely blocking UI updates like spinner animation.
You could recode something like this:
[activitySpinner startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAULT, 0), ^{
[self implementLogin];
dispatch_async(dispatch_get_main_queue(), ^{
// Stops spinner
[activitySpinner stopAnimating];
}
}
[Code is untested, but you get the idea.]
What is happening here is that you are dispatching the login task to the background, and the last thing that block will do is stop the spinner on the main thread (as a separate task).
Without more code, one can only guess the reason why it doesn't work.
I assume 'Beginning Spinner' output correctly(?)
If so, you probably didn't properly initialize the UIActivityIndicatorView.
Does it look like this?
activitySpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activitySpinner.hidesWhenStopped = YES;
[view addSubview:activitySpinner];

Adding "Breakpoint" or Pause in iPhone App

I have an app that is continuously taking in images from the video buffer (using the process described here: http://www.benjaminloulier.com/articles/ios4-and-direct-access-to-the-camera) and performing various processing on the most recent image in the buffer. For my particular application, when something noteworthy is found in the image, I want to display this information to the user and have the user decide whether the information is correct or not.
I want to display 2 UIButtons on the screen when this information is returned and it is at this point that I wish the code to "pause" (like a runtime breakpoint) and wait to see which button the user clicks before resuming. After clicking a button, the buttons will disappear.
The reason for this is I can't have the camera continue to acquire images and process them while I am waiting for the user input.
Thanks!
EDIT:
Here is what my code basically looks like:
if (continueRunningScript == YES) {
NSString *results = [self processImage];
[self displayResults: results];
// Show pause button
dispatch_async(dispatch_get_main_queue(), ^{
[pauseButton setHidden: NO];
});
}
and the pause button code:
- (UIAction) pauseButtonPress:(id) sender {
[pauseButton setHidden: YES];
[playButton setHidden: NO];
continueRunningScript = NO;
}
and the play button code:
- (UIAction) playButtonPress:(id) sender {
[playButton setHidden:YES];
continueRunningScript = YES;
}
Where could I add more boolean to handle the delay?

Why does my UIAlertView only appear after a delay?

In example code below UIAlertView is show after delay, but i need display it immediately
//metoda zapisuje komentrz na serwerze
-(void) saveAction {
UIAlertView *progressAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"imageGalleries.sendAction", #"") message:#" " delegate:self cancelButtonTitle:NSLocalizedString(#"alert.cancel", #"") otherButtonTitles:nil];
[progressAlert addSubview:progressView];
[progressAlert show];
// some long performance instructions
}
- (void)loadView {
[super loadView];
self.navigationItem.rightBarButtonItem = [NavButton buttonWithTitle:NSLocalizedString(#"sendImage.saveButtonTitle", #"") target:self action:#selector(saveAction)];
progressView = [[UIProgressView alloc] initWithFrame: CGRectMake(30.0f, 80.0f - 26, 225.0f, 10.0f)];
}
Why UIAlertView do not show immediately when I call saveAction?
If the “long performance instructions” following the alert code run on the main thread, they will block the alert from appearing. Read something about Cocoa run loops, that should make things more clear. (Essentially it could be said that all the UI instructions in your method are not performed immediately – they have to wait for the method to end, and then the main run loop picks them up and runs them.)
The code could better look like this:
- (void) startSomeLongOperation {
[self createAndDisplayProgressSpinner];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_NORMAL, 0), ^{
// …do something that takes long…
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissProgressSpinner];
});
});
}
This moves the long operation into background, so that the main thread can continue executing immediately.
Have you considered using MBProgressHUD for long lasting operations? It'll wrap those calls into separate threads for you and is very flexible from functionality and UI perspectives
I don't think you need to call
[progressAlert addSubview:progressView];
Aside from that, it really should just appear...
If you show the alert in background thread, it will also have a delay.

Dispatch_async and UI

I made alert informing user about saving action, i add it to view, save some image and dismiss alert. However it's not working in the way i hoped it would. Looking at code below ofc firstly in console i get "saved.." then "dispath". I would like to get opposite effect firstly get "dispath" then "saved.." (so write alert on screen, then save in background and finally dismiss alert). But i change image of imageView1, so i cant move merging out of dispath_async because its an UI action.. how to do it then..? I need to firstly merge images and after it to save them and all of this calculating time to keep alert in front.
//adding alert to view
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
dispatch_async(dispatch_get_main_queue(), ^{
//i want this to complete->
imageView1.image = [self merge:imageView1.image and:imageView2.image];
NSLog(#"dispatch");
});
//and then to do this action->
UIImageWriteToSavedPhotosAlbum(imageView1.image, self, #selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
NSLog(#"saved..");
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissWithClickedButtonIndex:0 animated:YES];
});
});
You should simply use dispatch_sync instead of dispatch_async. That function will not return until the block has executed on the main thread.