How to call a method after asynchronous task is complete

Posted by doctordoder on Stack Overflow See other posts from Stack Overflow or by doctordoder
Published on 2014-06-10T01:35:51Z Indexed on 2014/06/10 3:25 UTC
Read the original article Hit count: 164

I have a class called WikiWebView which is a subclass of UIWebView which loads Wikipedia subjects and is designed to fetch all the links of the webpage, in order to create a sort of site map for the subject. My problem is that I can only create the links once the web page has loaded, but the loading isn't done right after [self loadRequest:requestObj] is called.

- (void)loadSubject:(NSString *)subject
{
    // load the actual webpage
    NSString *wiki = @"http://www.wikipedia.org/wiki/";
    NSString *fullURL = [wiki stringByAppendingString:subject];
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [self loadRequest:requestObj];

    // [self createLinks]; // need this to be called after the view has loaded
}


- (void)createLinks
{
    NSString *javascript =
    @"var string = \"\";"
    "var arr = document.getElementsByClassName(\"mw-redirect\");"
    "for (var i = 0; i < arr.length; ++i)"
    "{"
    "var redirectLink = arr[i].href;"
    "string = string + redirectLink + \" \";"
    "}"
    "string;";
    NSString *links = [self stringByEvaluatingJavaScriptFromString:javascript];
    self.links = [links componentsSeparatedByString:@" "];
}

I tried the normal delegation technique, which lead to this code being added:

- (id)init
{
    if (self = [super init])
    {
        self.delegate = self;    // weird
    }

    return self;
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    ++_numProcesses;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    --_numProcesses;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    --_numProcesses;
    if (_numProcesses == 0) {
        [self createLinks];
    }
}

However, the delegate methods are never called..

I've seen similar questions where the answers are to use blocks, but how would I do that in this case?

© Stack Overflow or respective owner

Related posts about ios

Related posts about objective-c