简体   繁体   中英

How to present AlertController 2 seconds after click a button

I want to present an alert view after the user click on a button at 2s. The function is to start calibration, and I want to show the user that calibration is done after 2s.

I'm counting in an array that when it reaches 20 (presents 2s), and I used

if showCalibDone {

    let calibDoneAlert = UIAlertController(title: "", message: "Calibration is finished", preferredStyle: .Alert)

    calibDoneAlert.addAction(UIAlertAction(title: "", style: .Default, handler: {(action: UIAlertAction!) in

        self.x0 = self.average40(self.xCalibrate)

        self.presentViewController(calibDoneAlert, animated: true, completion: nil)

    }))

This is the counting. xCalibrate is an array which will add an object each time the accelerometer updates.

if xCalibrate.count == 40 {

                println("40 achieved")
                self.showCalibDone = true
}

But the alert view never appears with this if condition. I tried to put it in viewWillAppear or viewDidLoad , but it seems both are not correct.

How can I get this 'loop' be executed? Where should I put it? Or maybe I should use a timer to count?

If you just want some code to be executed after some a delay, use dispatch_after:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue()) {
    // ...
}

You can also use performSelector to achieve the same results

- (void) showAlert
{
  [[[UIAlertView alloc] initWithTitle:@"Title" message:@"Some message" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil] show];
}

//

[self performSelector:@selector(showAlert) withObject:nil afterDelay:2.0f];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM