【问题标题】:How to call a method after asynchronous task is complete异步任务完成后如何调用方法
【发布时间】:2014-06-10 01:35:51
【问题描述】:

我有一个名为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.

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

【问题讨论】:

  • “它不起作用”是一个无用的声明。告诉我们您发布的代码的结果是什么。你收到错误了吗?是否调用了任何委托方法?具体一点。
  • @rdelmar "it doesn't work" 是指向另一个问题的链接,其中设置 self.delegate = self 会导致无限倒退。
  • 如果一个 web 视图不能是它自己的委托,那么你的子类也不能。如何创建一个不同的类作为委托并扫描其中的链接?
  • @danh 我宁愿有一些不会将我的代码拆分到不同位置的东西。
  • @doctordoder,代理可以在同一个文件中定义。

标签: ios objective-c asynchronous uiwebview


【解决方案1】:

使用一个模块中的代码,您可以规避 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

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 2020-09-08
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    相关资源
    最近更新 更多