如何在异步任务完成后调用方法

时间:2014-06-10 01:35:52

标签: ios objective-c asynchronous uiwebview

我有一个名为WikiWebView的类,它是UIWebView的子类,它加载维基百科主题,旨在获取网页的所有链接,以便为其创建一种站点地图。学科。我的问题是,我只能在网页加载后创建链接,但是在调用[self loadRequest:requestObj]后没有立即加载。

- (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:@" "];
}

我尝试了正常的delegation technique,这导致添加了此代码:

- (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];
    }
}

然而,the delegate methods are never called.

我已经看到类似的问题,答案是使用块,但在这种情况下我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用一个模块中的代码,您可以规避Web视图的问题,因为它是自己的代理......

@interface MyCustomDelegate : NSObject <UIWebViewDelegate>
@end

@implementation MyWebViewSublcass

    // ...
    self.delegate = [[MyCustomDelegate alloc] init];

@end

@implementation MyCustomDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // do your scan for links here
}

@end