如何在webViewDidFinishLoad中运行一次命令?

时间:2017-05-29 06:57:13

标签: ios objective-c xcode webview uiwebview

我发现很难在webViewDidFinishLoad中运行一次警报,这是第一次,当应用程序打开并且webViewDidFinishLoad完成加载时。问题是,我使用webview并经常更新。我知道如何确保命令在应用程序生命周期中只运行一次,但我需要每次加载应用程序时都使用该命令专门运行ONCE并且它必须在webViewDidFinishLoad中。任何帮助将不胜感激。现在,这是我需要在webViewDidFinishLoad中的每个应用程序的开头运行一次的代码:

[activityind stopAnimating];

    UIAlertController *alert = [UIAlertController
                                alertControllerWithTitle:NSLocalizedString(@"Are you ready to get directions?", @"The title of an alert that tells the user, that no server was set.")
                                message:NSLocalizedString(@"Click 'LAUNCH IT' and we'll do all the work! ", @"The message of an alert that tells the user, that no server was set.")
                                preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *ok = [UIAlertAction
                         actionWithTitle:NSLocalizedString(@"LAUNCH IT!", @"A common affirmative action title, like 'OK' in english.")
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                             AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

                             NSURL *URL = [NSURL URLWithString:@"https://dotcom.com/In.js"];
                             NSURLRequest *request = [NSURLRequest requestWithURL:URL];

                             NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                 NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                                 // Save this following url to load the file
                                 return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
                             } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                                 NSLog(@"BLAST OFF! IN CODE HAS LANDED :)");
                             }];
                             [downloadTask resume];
                             NSString *javaScript = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error: nil];

                             [_viewWeb stringByEvaluatingJavaScriptFromString:javaScript];

                             NSString *jsString = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"PrivacyView" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil];
                             [_viewWeb stringByEvaluatingJavaScriptFromString:jsString];
                             NSLog(@"PRIVACY VIEW!: %@", [[NSUserDefaults standardUserDefaults] objectForKey:LAUNCH_KEY]);
                         }];
    UIAlertAction *dontshowagain = [UIAlertAction
                                    actionWithTitle:NSLocalizedString(@"Don't Show Again", @"A common affirmative action title, like 'OK' in english.")
                                    style:UIAlertActionStyleDefault
                                    handler:^(UIAlertAction * action)
                                    {
                                        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"alert"];
                                        [[NSUserDefaults standardUserDefaults] synchronize];

                                    }];

    [alert addAction:ok];
    [alert addAction:dontshowagain];

    [self.parentViewController presentViewController:alert animated:YES completion:nil];


}

3 个答案:

答案 0 :(得分:2)

您可以使用dispatch_once_t

  

执行一次块对象,并且只执行一次   应用

https://developer.apple.com/reference/dispatch/1447169-dispatch_once

示例

static dispatch_once_t once;
dispatch_once(&once, ^{
    // Your code
});

答案 1 :(得分:1)

您可以制作一个BOOL属性并在webViewDidFinishLoad内进行比较。

@interface YourViewController ()<UIWebViewDelegate> {
    BOOL isAlertShown;
}     
@end

@implementation YourViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //Set isAlertShown to false
    isAlertShown = NO;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (!isAlertShown) {
        isAlertShown = YES;
        //Show alert here
    }
}
@end

答案 2 :(得分:1)

第一个方法

使用 BOOL实例变量检查警报是否已经显示。

示例:

@implementation ViewController () {
    BOOL shownAlertOnce;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    //your code here.......
    if (shownAlertOnce == NO) {
        [self.parentViewController presentViewController:alert animated:YES completion:nil];
        shownAlertOnce = YES;
    }
}

@end

第二个方法

使用dispatch_once

示例:

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    //your code here.......

    static dispatch_once_t once;
    dispatch_once(&once, ^{
        [self.parentViewController presentViewController:alert animated:YES completion:nil]; 
    });
}

注意:虽然第二种方法很简单,但要注意理想情况下应该避免多线程之间的竞争条件。

因此,如果您的代码是由单个线程访问的,那么首选方法,否则为2nd。