1. 程式人生 > >iOS網路3—UIWebView與WKWebView使用詳解

iOS網路3—UIWebView與WKWebView使用詳解

複製程式碼
/// 控制元件高度
#define kSearchBarH  44
#define kBottomViewH 44

/// 螢幕大小尺寸
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

#import "ViewController.h"
#import <WebKit/WebKit.h>


@interface ViewController () <UISearchBarDelegate, WKNavigationDelegate>

@property (nonatomic, strong) UISearchBar 
*searchBar; /// 網頁控制導航欄 @property (weak, nonatomic) UIView *bottomView; @property (nonatomic, strong) WKWebView *wkWebView; @property (weak, nonatomic) UIButton *backBtn; @property (weak, nonatomic) UIButton *forwardBtn; @property (weak, nonatomic) UIButton *reloadBtn; @property (weak, nonatomic) UIButton
*browserBtn; @property (weak, nonatomic) NSString *baseURLString; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // [self simpleExampleTest]; [self addSubViews]; [self refreshBottomButtonState]; [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:
@"http://www.cnblogs.com/mddblog/"]]]; } - (void)simpleExampleTest { // 1.建立webview,並設定大小,"20"為狀態列高度 WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)]; // 2.建立請求 NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]; // // 3.載入網頁 [webView loadRequest:request]; // [webView loadFileURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"] allowingReadAccessToURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]]; // 最後將webView新增到介面 [self.view addSubview:webView]; } /// 模擬器載入mac本地檔案 - (void)loadLocalFile { // 1.建立webview,並設定大小,"20"為狀態列高度 WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)]; // 2.建立url userName:電腦使用者名稱 NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]; // 3.載入檔案 [webView loadFileURL:url allowingReadAccessToURL:url]; // 最後將webView新增到介面 [self.view addSubview:webView]; } - (void)addSubViews { [self addBottomViewButtons]; [self.view addSubview:self.searchBar]; [self.view addSubview:self.wkWebView]; } - (void)addBottomViewButtons { // 記錄按鈕個數 int count = 0; // 新增按鈕 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setTitle:@"後退" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [button.titleLabel setFont:[UIFont systemFontOfSize:15]]; button.tag = ++count; // 標記按鈕 [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside]; [self.bottomView addSubview:button]; self.backBtn = button; button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setTitle:@"前進" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [button.titleLabel setFont:[UIFont systemFontOfSize:15]]; button.tag = ++count; [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside]; [self.bottomView addSubview:button]; self.forwardBtn = button; button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setTitle:@"重新載入" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [button.titleLabel setFont:[UIFont systemFontOfSize:15]]; button.tag = ++count; [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside]; [self.bottomView addSubview:button]; self.reloadBtn = button; button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setTitle:@"Safari" forState:UIControlStateNormal]; [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; [button.titleLabel setFont:[UIFont systemFontOfSize:15]]; button.tag = ++count; [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside]; [self.bottomView addSubview:button]; self.browserBtn = button; // 統一設定frame [self setupBottomViewLayout]; } - (void)setupBottomViewLayout { int count = 4; CGFloat btnW = 80; CGFloat btnH = 30; CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2; // 按鈕間間隙 CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count; CGFloat btnX = margin * 0.5; self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH); btnX = self.backBtn.frame.origin.x + btnW + margin; self.forwardBtn.frame = CGRectMake(btnX, btnY, btnW, btnH); btnX = self.forwardBtn.frame.origin.x + btnW + margin; self.reloadBtn.frame = CGRectMake(btnX, btnY, btnW, btnH); btnX = self.reloadBtn.frame.origin.x + btnW + margin; self.browserBtn.frame = CGRectMake(btnX, btnY, btnW, btnH); } /// 重新整理按鈕是否允許點選 - (void)refreshBottomButtonState { if ([self.wkWebView canGoBack]) { self.backBtn.enabled = YES; } else { self.backBtn.enabled = NO; } if ([self.wkWebView canGoForward]) { self.forwardBtn.enabled = YES; } else { self.forwardBtn.enabled = NO; } } /// 按鈕點選事件 - (void)onBottomButtonsClicled:(UIButton *)sender { switch (sender.tag) { case 1: { [self.wkWebView goBack]; [self refreshBottomButtonState]; } break; case 2: { [self.wkWebView goForward]; [self refreshBottomButtonState]; } break; case 3: [self.wkWebView reload]; break; case 4: [[UIApplication sharedApplication] openURL:self.wkWebView.URL]; break; default: break; } } #pragma mark - WKWebView WKNavigationDelegate 相關 /// 是否允許載入網頁 在傳送請求之前,決定是否跳轉 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *urlString = [[navigationAction.request URL] absoluteString]; urlString = [urlString stringByRemovingPercentEncoding]; // NSLog(@"urlString=%@",urlString); // 用://擷取字串 NSArray *urlComps = [urlString componentsSeparatedByString:@"://"]; if ([urlComps count]) { // 獲取協議頭 NSString *protocolHead = [urlComps objectAtIndex:0]; NSLog(@"protocolHead=%@",protocolHead); } decisionHandler(WKNavigationActionPolicyAllow); } #pragma mark - searchBar代理方法 /// 點選搜尋按鈕 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { // 建立url NSURL *url = nil; NSString *urlStr = searchBar.text; // 如果file://則為開啟bundle本地檔案,http則為網站,否則只是一般搜尋關鍵字 if([urlStr hasPrefix:@"file://"]){ NSRange range = [urlStr rangeOfString:@"file://"]; NSString *fileName = [urlStr substringFromIndex:range.length]; url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil]; // 如果是模擬器載入電腦上的檔案,則用下面的程式碼 // url = [NSURL fileURLWithPath:fileName]; }else if(urlStr.length>0){ if ([urlStr hasPrefix:@"http://"]) { url=[NSURL URLWithString:urlStr]; } else { urlStr=[NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@",urlStr]; } urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; url=[NSURL URLWithString:urlStr]; } NSURLRequest *request=[NSURLRequest requestWithURL:url]; // 載入請求頁面 [self.wkWebView loadRequest:request]; } #pragma mark - 懶載入 - (UIView *)bottomView { if (_bottomView == nil) { UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)]; view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1]; [self.view addSubview:view]; _bottomView = view; } return _bottomView; } - (UISearchBar *)searchBar { if (_searchBar == nil) { UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kSearchBarH)]; searchBar.delegate = self; searchBar.text = @"http://www.cnblogs.com/mddblog/"; _searchBar = searchBar; } return _searchBar; } - (WKWebView *)wkWebView { if (_wkWebView == nil) { WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20 + kSearchBarH, kScreenWidth, kScreenHeight - 20 - kSearchBarH - kBottomViewH)]; webView.navigationDelegate = self; // webView.scrollView.scrollEnabled = NO; // webView.backgroundColor = [UIColor colorWithPatternImage:self.image]; // 允許左右劃手勢導航,預設允許 webView.allowsBackForwardNavigationGestures = YES; _wkWebView = webView; } return _wkWebView; } @end
複製程式碼

相關推薦

iOS網路3UIWebViewWKWebView使用

/// 控制元件高度 #define kSearchBarH 44 #define kBottomViewH 44 /// 螢幕大小尺寸 #define kScreenWidth [UIScreen mainScreen].bounds.size.width #define kScreenHeigh

關於iOS網路音訊播放的一些(使用AVPlayer播放網路音訊)

在日常的iOS開發中,我們通常會遇到媒體播放的問題,XCode中已經為我們提供了功能非常強大的AVFoundation框架和MediaPlayer框架.其中AVFoundation框架中的AVAudioPlayer主要

3分鐘實現iOS語言本地化/國際化(圖文

返回 sch 信息 con ren obj end xib standard 前言 語言本地化,又叫做語言國際化。 是指根據用戶操作系統的語言設置,自動將應用程序的語言設置為和用戶操作系統語言一致的語言。 往往一些應用程序需要提供給多個國家的人群使用,或者一個國家有多種

iOSUIWebViewWKWebView、JavaScriptOC互動、Cookie管理看我就夠(下)

前言在前面的文章中,我們介紹了UIWebView、WKWebView一些使用,與JS的互動和一些坑,相信看過的小夥伴們,已經大概清楚了吧,如果有問題,歡迎提問。本文是本系列文章的最後一篇,主要為小夥伴們分享下Safari除錯、與前端的配合以及實際應用中一些需求的實現等:關於文

iOS (一) - UIWebView WKWebView . 基本使用

隨說 : 最近有個需求,是將公司的一個內網的頁面巢狀在app中作為一個模組.這不是很簡單的webView請求一下就行了麼?其實內裡大有乾坤.自己也將思路整理一遍 UIWebView UIWebView的基本使用方法 : 就這樣就已經整整個baidu的頁面展示到app上 下面我們看一下we

iOSUIWebView的使用及利用webview實現圖文混排例項

iOS中UIWebView的使用詳解 一、初始化與三種載入方式      UIWebView繼承與UIView,因此,其初始化方法和一般的view一樣,通過alloc和init進行初始化,其載入資料的方式有三種: 第一種: - (void)loadRequest:(NSU

ios WKWebView

    專案中,使用到web載入,是件再正常不過的事情.之前一直使用UIWebView.但ios8後,蘋果推出了WKWebView.效能優化更加完善.並以更加穩定,載入滑動等功能方面更加流暢,記憶體佔

Java網路程式設計NIO4:淺析NIO包中的Buffer、Channel 和 Selector

Java NIO:Buffer、Channel 和 Selector轉自https://www.javadoop.com/post/nio-and-aio本文將介紹 Java NIO 中三大元件 Buffer、Channel、Selector 的使用。本來要一起介紹非阻塞 I

異常處理MiniDump-(3)SHE(Structured Exception Handling)

The __leave keyword is valid within a try-finally statement block. The effect of __leave is to jump to the end of the try-finally block. The termination ha

ios UIWebview 載入頁面(二)

設定背景透明 設定webview的backgroundColor屬性為[UIColor clearColor]; ? 1 webView.backgroundColor = [UIColor clearColor]; 為webview中的HTML頁面

Java網路程式設計NIO2:JAVA NIO 一步步構建I/O多路複用的請求模型

微信公眾號【黃小斜】作者是螞蟻金服 JAVA 工程師,專注於 JAVA 後端技術棧:SpringBoot、SSM全家桶、MySQL、分散式、中介軟體、微服務,同時也懂點投資理財,堅持學習和寫作,相信終身學習的力量!關注公眾號後回覆”架構師“即可領取 Java基礎、進階、專案和架構師等免費學習資料,更有資料

Java網路程式設計NIO8:淺析mmap和Direct Buffer

微信公眾號【黃小斜】作者是螞蟻金服 JAVA 工程師,目前在螞蟻財富負責後端開發工作,專注於 JAVA 後端技術棧,同時也懂點投資理財,堅持學習和寫作,用大廠程式設計師的視角解讀技術與網際網路,我的世界裡不只有 coding!關注公眾號後回覆”架構師“即可領取 Java基礎、進階、專案和架構師等免費學習資

Javascript中的applycall

選項 this 模式 div sun fun object 面向 傳遞     JavaScript中有一個call和apply方法,其作用基本相同,但也有略微的區別。  一、方法定義   1、call 方法   語法:call([thisObj[,arg1[, arg2[

letconst

沒有 而在 不能 解析 引入 cti lar 語言 reference 在ES6中,js首次引入了塊級作用域的概念,而什麽是塊級作用域? 眾所就知,在js當中存在預解析的概念,就是變量提升。並且只存在全局作用域和私有作用域。在全局定義的變量就是全局變量,而在函數內部定義的

MySQL5.6 數據庫主從(Master/Slave)同步安裝配置

inux bind 主從配置 希望 master 強調 數據庫主從 ria 配置文件 目錄(?)[+] 安裝環境 操作系統 :CentOS 6.5 數據庫版本:MySQL 5.6.27 主機A:192.168.1.1 (Master) 主機B:192.168.

Js中JSON.stringify()JSON.parse()eval()及使用案例

div 網絡 blog 處理 ive asc 還要 ava 不同 JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。因為采用獨立於語言的文本格式,也使用了類似於C語言家族的習慣,擁有了這些特性使使JSON稱為理想的數據交換語言,作用

AngularJS 過濾排序及實例代碼

highlight 進行 angularjs ngs key 管道命令 個數 變量 數據 這篇文章主要介紹了AngularJS 過濾與排序,實現查詢過濾以及排序的功能。 通過這篇文章可以了解到   1、 angularjs的過濾器   2、 ng-repeat的使用方法

lucene、lucene.NET詳細使用優化[轉]

構造 bitset 更多 隱患 .net wrapper 屬性設置 似的 擔心 1 lucene簡介1.1 什麽是luceneLucene是一個全文搜索框架,而不是應用產品。因此它並不像www.baidu.com 或者google Desktop那麽拿來就能用,它只是提供了

CentOS 6.x上搭建vSFTPD服務器搭建配置

服務器 故障排查 運維 vsftpd 摘要: 手把手教你搭建vsftpd服務器,實現了基於db文件和MySQL數據庫文件進行虛擬用戶認證,當然了也本文章也包含搭建過程中問題的排查啦,哈哈哈。 另外,我在CentOS 7.x上也進行了搭建測試,步驟一致,個別命令會有不

[js高手之路]原型對象(prototype)原型鏈相關屬性方法

隱式 之前 username tar uname create pro getproto .get 一,instanceof: instanceof檢測左側的__proto__原型鏈上,是否存在右側的prototype原型. 我在之前的兩篇文章 [js高手之路]構造函數的基