Search code examples
objective-cuibuttonibaction

Stop IBAction from another Button Objective-C


I do not know how to stop the IBAction. What I need: I press the button, and then call the IBAction that runs about 5 minutes. I want to make the cancel button, when pressed, will stop IBAction from the first button.

How do I do this?

Code:

- (IBAction)download:(id)sender {


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {

        // Determile cache file path
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);


        for (i=0;i<=7;i++) {

            //Updating progressView and progressLabel

            dispatch_async(dispatch_get_main_queue(), ^ {
                progressSlider.progress = (float)i/(float)299;
                progressLabel.text = [NSString stringWithFormat:@"Загружено: %d из 299",i];
            });

            NSString *filePath = [NSString stringWithFormat:@"%@/avto-0-%d.html", [paths objectAtIndex:0],i];

            // Download and write to file
            NSString *mustUrl = [NSString stringWithFormat:@"http://www.mosgortrans.org/pass3/shedule.php?type=avto&%@", [listOfAvtoUrl objectAtIndex:i]];
            NSURL *url = [NSURL URLWithString:mustUrl];
            NSData *urlData = [NSData dataWithContentsOfURL:url];


            [urlData writeToFile:filePath atomically:YES];

        }

    });


}

Solution

  • Call another function which runs the code in a separate thread when IBAction clicked. Now you can stop/cancel the thread if you need.