iOS如何向UIWebView loadRequest添加完成块:?

时间:2014-10-23 15:12:26

标签: ios objective-c asynchronous uiwebview objective-c-blocks

我正在使用UIWebView并且已经使用了带有可选块的webViewDidFinishLoad:方法,该块在加载完成后执行:

    -(void)webViewDidFinishLoad:(UIWebView *)webView
    {
        [super webViewDidFinishLoad:webView];

//... bunch of other code        

        if(self.webViewFinishLoadBlock != nil)
        {
            self.webViewFinishLoadBlock();
        }
    }

现在我正在使用更复杂的加载页面和重定向序列,这使得上面的逻辑不够充分。我不想将自己注册为dummyWebView的委托,并且必须处理存储在我的视图控制器属性中的多个完成块:

    dummyWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    [dummyWebView loadRequest:[NSURLRequest requestWithURL:logoutURL]];
//Ideally here I would know when dummyWebView finishes loading, because there's some code I want to execute once it is done

我的问题是:

是否有某种第三方框架允许我使用loadRequest:withCompletion:来简化编写回调代码?

2 个答案:

答案 0 :(得分:5)

你可以:

  • 子类UIWebView,其中包含保存webViewDidFinish完成块的属性;

  • 确保指定其委托;

  • 实现webViewDidFinish就像你写的那样(虽然我建议块返回web视图和NSError对象,如果有的话);以及

  • 也实施webView:didFailLoadWithError:

因此:

//  MyWebView.h

#import <UIKit/UIKit.h>

typedef void(^WebViewFinishLoadBlock)(UIWebView *, NSError *);

@interface MyWebView : UIWebView

@property(nonatomic, copy) WebViewFinishLoadBlock webViewFinishLoadBlock;

- (void)loadRequest:(NSURLRequest *)request withCompletionHandler:(WebViewFinishLoadBlock)completionHandler;

@end

//  MyWebView.m

#import "MyWebView.h"

@interface MyWebView () <UIWebViewDelegate>
@end

@implementation MyWebView

- (void)loadRequest:(NSURLRequest *)request withCompletionHandler:(WebViewFinishLoadBlock)completionHandler
{
    self.delegate = self;
    self.webViewFinishLoadBlock = completionHandler;

    [self loadRequest:request];
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (self.webViewFinishLoadBlock) {
        self.webViewFinishLoadBlock(webView, nil);
        self.webViewFinishLoadBlock = nil;
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (self.webViewFinishLoadBlock) {
        self.webViewFinishLoadBlock(webView, error);
        self.webViewFinishLoadBlock = nil;
    }
}

@end

然后:

MyWebView *webView = [[MyWebView alloc] init];
webView.frame = self.view.bounds;
[self.view addSubview:webView];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request withCompletionHandler:^(UIWebView *webView, NSError *error) {
    if (error) {
        NSLog(@"failed: %@", error);
    } else {
        NSLog(@"succeeded");
    }
}];

答案 1 :(得分:4)

- (void)webViewDidFinishLoad:(UIWebView *)webView

是委托方法。按照惯例,委托方法要求对象将自身传递回委托:

(UIWebView*)webView

通过参数。

如果我们想要使用属性request:获取最后一个请求参数,这意味着webView.request.URL

父对象可以是多个对象的委托,它可以识别从该参数获得响应的对象。要么打开响应你的东西,要么建立一些基础设施来更优雅地处理它。