iOS開發(fā):給UIWebview的導航欄添加返回、關閉按鈕

在我們平日的開發(fā)中,不免有原生與H5的交互,比如說:從原生頁面的一個按鈕,點擊之后跳轉到了一個H5的頁面A,A頁面中又有一個按鈕,點擊之后,又加載了一個新的H5頁面B,從B點擊一個按鈕,又加載一個新的H5頁面C,如果此時我們點擊左上角的返回按鈕,會直接返回到我們的原生頁面;

是不是上面給用戶的體驗很不好(當然殘品經理會覺得是,我們都是無所謂的啦),此時我們想要重新定制返回按鈕,我們想要從C頁面判斷是否還有上一級H5頁面可供返回,如果有上一級頁面還是H5,點擊左上角的返回則返回到B頁面,并且在B頁面的左上角加上一個關閉按鈕,這個關閉按鈕的作用主要是為了關閉所有的H5的頁面,直接返回到我們原生的頁面;如果我們不點擊關閉按鈕,還是點擊返回,則從B頁面返回到A頁面;再次點擊返回,則關閉了H5的頁面,回到了原生的頁面;

說的也許有點兒繞,不過大致思想就是:先判斷當前的H5頁面是否可以返回:

//判斷當前H5是否可以返回
[self.webView canGoBack]

如果可以返回,則返回到上一個H5頁面,并在左上角添加一個關閉按鈕,如果不可以返回,則直接:

//回到原生頁面
[self.navigationController popViewControllerAnimated:YES];

下面是我的主要實現(xiàn)代碼,我寫一個繼承與UIViewController的類,接受了UIWebviewDelegate,并定義了一個UIwebview的屬性,給外面留了一個方法,只需要傳遞一個URL,我們就可以加載;如果有地方需要加載H5的頁面,我們可以直接集成與這個類,這樣的好處在于方便維護;

當然我封裝的這個類,同時也是支持HTTPS的請求的;話不多說,代碼如下:

創(chuàng)建一個類,繼承與UIViewController,.h中的代碼

#import <UIKit/UIKit.h>

@interface SYWebViewController : UIViewController<UIWebViewDelegate, NSURLConnectionDelegate>

//定義一個屬性,方便外接調用
@property (nonatomic, strong) UIWebView *webView;

//聲明一個方法,外接調用時,只需要傳遞一個URL即可
- (void)loadHTML:(NSString *)htmlString;

@end

.m中的實現(xiàn)如下:

#import "SYWebViewController.h"

@interface NSURLRequest (InvalidSSLCertificate)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end

@interface SYWebViewController ()

@property (nonatomic, strong) NSURLRequest *request;
//判斷是否是HTTPS的
@property (nonatomic, assign) BOOL isAuthed;

//返回按鈕
@property (nonatomic, strong) UIBarButtonItem *backItem;
//關閉按鈕
@property (nonatomic, strong) UIBarButtonItem *closeItem;

@end

@implementation SYWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [self.view addSubview:self.webView];

    [self addLeftButton];
}

//加載URL
- (void)loadHTML:(NSString *)htmlString
{
    NSURL *url = [NSURL URLWithString:htmlString];
    self.request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
    [self.webView loadRequest:self.request];
}

#pragma mark - UIWebViewDelegate

//開始加載
- (BOOL)webView:(UIWebView *)awebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString* scheme = [[request URL] scheme];
    //判斷是不是https
    if ([scheme isEqualToString:@"https"]) {
        //如果是https:的話,那么就用NSURLConnection來重發(fā)請求。從而在請求的過程當中吧要請求的URL做信任處理。
        if (!self.isAuthed) {
            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            [conn start];
            [awebView stopLoading];
            return NO;
        }
    }
    return YES;
}

//設置webview的title為導航欄的title
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        self.isAuthed = YES;
        //NSURLCredential 這個類是表示身份驗證憑據不可變對象。憑證的實際類型聲明的類的構造函數來確定。
        NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"網絡不給力");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.isAuthed = YES;
    //webview 重新加載請求。
    [self.webView loadRequest:self.request];
    [connection cancel];
}

#pragma mark - 添加關閉按鈕

- (void)addLeftButton
{
    self.navigationItem.leftBarButtonItem = self.backItem;
}

//點擊返回的方法
- (void)backNative
{
    //判斷是否有上一層H5頁面
    if ([self.webView canGoBack]) {
          //如果有則返回
        [self.webView goBack];
        //同時設置返回按鈕和關閉按鈕為導航欄左邊的按鈕
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
        [self closeNative];
    }
}

//關閉H5頁面,直接回到原生頁面
- (void)closeNative
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - init

- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //這是一張“<”的圖片,可以讓美工給切一張
        UIImage *image = [UIImage imageNamed:@"sy_back"];
        [btn setImage:image forState:UIControlStateNormal];
        [btn setTitle:@"返回" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [btn setTitleColor:[UIColor sy_backColor] forState:UIControlStateNormal];
        //字體的多少為btn的大小
        [btn sizeToFit];
        //左對齊
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //讓返回按鈕內容繼續(xù)向左邊偏移15,如果不設置的話,就會發(fā)現(xiàn)返回按鈕離屏幕的左邊的距離有點兒大,不美觀
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
        btn.frame = CGRectMake(0, 0, 40, 40);
        _backItem.customView = btn;
    }
    return _backItem;
}

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"關閉" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
    }
    return _closeItem;
}

@end

具體的使用方法就是,創(chuàng)建一個類,繼承與這類:SYWebViewController

#import <UIKit/UIKit.h>
#import "SYWebViewController.h"

@interface SYFlashHTMLViewController : SYWebViewController

@end

然后在這個類的.m中的viewDidLoad中,調用父視圖加載URL的方法,即:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.delegate = self;
    [self loadHTML:self.htmlString];
}

效果如下圖:打開百度(圖片1),點擊圖片進入(圖片2),點擊返回返回到(圖片3),圖片1和圖片的區(qū)別在于多了個關閉按鈕:

[圖片上傳失敗...(image-2c7fcb-1520217790077)]

[圖片上傳失敗...(image-7e437a-1520217790077)]

[圖片上傳失敗...(image-35d61b-1520217790077)]


GitHub地址:Demo
純手打,喜歡點個贊,希望對看到的你有所幫助!

原作者:First灬DKS
鏈接:http://www.itdecent.cn/p/fa070e790647

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容