




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析
@interface
ViewController
()
@end
@implementation
ViewController
-
(void)viewDidLoad
{
[super
viewDidLoad];
//
區(qū)別于uiwebview
wkwebview使用如下方法攔截
Class
cls
=
NSClassFromString(@"WKBrowsingContextController");
SEL
sel
=
NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if
([(id)cls
respondsToSelector:sel])
{
[(id)cls
performSelector:sel
withObject:@"http"];
[(id)cls
performSelector:sel
withObject:@"https"];
}
}#
注冊NSURLProtocol攔截
-
(IBAction)regist:(id)sender
{
[NSURLProtocol
registerClass:[FilteredProtocol
class]];
}#
注銷NSURLProtocol攔截
-
(IBAction)unregist:(id)sender
{
[NSURLProtocol
unregisterClass:[FilteredProtocol
class]];
}-
(void)downloadZip
{
NSDictionary
*_headers;
NSURLSession
*_session
=
[self
sessionWithHeaders:_headers];
NSURL
*url
=
[NSURL
URLWithString:
@"25:3238/dist.zip"];
NSMutableURLRequest
*request
=
[NSMutableURLRequest
requestWithURL:url];
//
初始化cachepath
NSString
*cachePath
=
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask,
YES)
lastObject];
NSFileManager
*fm
=
[NSFileManager
defaultManager];
//
刪除之前已有的文件
[fm
removeItemAtPath:[cachePath
stringByAppendingPathComponent:@"dist.zip"]
error:nil];
NSURLSessionDownloadTask
*downloadTask=[_session
downloadTaskWithRequest:request
completionHandler:^(NSURL
*location,
NSURLResponse
*response,
NSError
*error)
{
if
(!error)
{
NSError
*saveError;
NSURL
*saveUrl
=
[NSURL
fileURLWithPath:
[cachePath
stringByAppendingPathComponent:@"dist.zip"]];
//
location是下載后的臨時保存路徑,需要將它移動到需要保存的位置
[[NSFileManager
defaultManager]
copyItemAtURL:location
toURL:saveUrl
error:&saveError];
if
(!saveError)
{
NSLog(@"task
ok");
if([SSZipArchive
unzipFileAtPath:
[cachePath
stringByAppendingPathComponent:@"dist.zip"]
toDestination:cachePath])
{
NSLog(@"unzip
ok");//
解壓成功
}
else
{
NSLog(@"unzip
err");//
解壓失敗
}
}
else
{
NSLog(@"task
err");
}
}
else
{
NSLog(@"error
is
:%@",
error.localizedDescription);
}
}];
[downloadTask
resume];
}-
(void)migrateDistToTempory
{
NSFileManager
*fm
=
[NSFileManager
defaultManager];
NSString
*cacheFilePath
=
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask,
YES)
lastObject]
stringByAppendingPathComponent:@"dist"];
NSString
*tmpFilePath
=
[NSTemporaryDirectory()
stringByAppendingPathComponent:@"dist"];
//
先刪除tempory已有的dist資源
[fm
removeItemAtPath:tmpFilePath
error:nil];
NSError
*saveError;
//
從caches拷貝dist到tempory臨時文件夾
[[NSFileManager
defaultManager]
copyItemAtURL:[NSURL
fileURLWithPath:cacheFilePath]
toURL:[NSURL
fileURLWithPath:tmpFilePath]
error:&saveError];
NSLog(@"Migrate
dist
to
tempory
ok");
}//
//
ProtocolCustom.m
//
proxy-browser
//
//
Created
by
melo的微博
on
2018/4/8.
//
Copyright
©
2018年
com.
All
rights
reserved.
//
#import
<objc/runtime.h>
#import
<Foundation/Foundation.h>
#import
<MobileCoreServices/MobileCoreServices.h>
static
NSString*const
matchingPrefix
=
@"25:3233/static/";
static
NSString*const
regPrefix
=
@"25:3233";
static
NSString*const
FilteredKey
=
@"FilteredKey";
@interface
FilteredProtocol
:
NSURLProtocol
@property
(nonatomic,
strong)
NSMutableData
*responseData;
@property
(nonatomic,
strong)
NSURLConnection
*connection;
@end
@implementation
FilteredProtocol
+
(BOOL)canInitWithRequest:(NSURLRequest
*)request
{
return
[NSURLProtocol
propertyForKey:FilteredKey
inRequest:request]==
nil;
}
+
(NSURLRequest
*)canonicalRequestForRequest:(NSURLRequest
*)request
{
NSLog(@"Got
it
request.URL.absoluteString
=
%@",request.URL.absoluteString);
NSMutableURLRequest
*mutableReqeust
=
[request
mutableCopy];
//截取重定向
if
([request.URL.absoluteString
hasPrefix:matchingPrefix])
{
NSURL*
proxyURL
=
[NSURL
URLWithString:[FilteredProtocol
generateProxyPath:
request.URL.absoluteString]];
NSLog(@"Proxy
to
=
%@",
proxyURL);
mutableReqeust
=
[NSMutableURLRequest
requestWithURL:
proxyURL];
}
return
mutableReqeust;
}
+
(BOOL)requestIsCacheEquivalent:(NSURLRequest
*)a
toRequest:(NSURLRequest
*)b
{
return
[super
requestIsCacheEquivalent:a
toRequest:b];
}
#
如果[index.html]結(jié)尾
=>
就直接[Load]本地[index.html]
-
(void)startLoading
{
NSMutableURLRequest
*mutableReqeust
=
[[self
request]
mutableCopy];
//
標(biāo)示改request已經(jīng)處理過了,防止無限循環(huán)
[NSURLProtocol
setProperty:@YES
forKey:FilteredKey
inRequest:mutableReqeust];
if
([self.request.URL.absoluteString
hasSuffix:@"index.html"])
{
NSURL
*url
=
self.request.URL;
NSString
*path
=
[FilteredProtocol
generateDateReadPath:
self.request.URL.absoluteString];
NSLog(@"Read
data
from
path
=
%@",
path);
NSFileHandle
*file
=
[NSFileHandle
fileHandleForReadingAtPath:path];
NSData
*data
=
[file
readDataToEndOfFile];
NSLog(@"Got
data
=
%@",
data);
[file
closeFile];
//3.拼接響應(yīng)Response
NSInteger
dataLength
=
data.length;
NSString
*mimeType
=
[self
getMIMETypeWithCAPIAtFilePath:path];
NSString
*httpVersion
=
@"HTTP/1.1";
NSHTTPURLResponse
*response
=
nil;
if
(dataLength
>
0)
{
response
=
[self
jointResponseWithData:data
dataLength:dataLength
mimeType:mimeType
requestUrl:url
statusCode:200
httpVersion:httpVersion];
}
else
{
response
=
[self
jointResponseWithData:[@"404"
dataUsingEncoding:NSUTF8StringEncoding]
dataLength:3
mimeType:mimeType
requestUrl:url
statusCode:404
httpVersion:httpVersion];
}
//4.響應(yīng)
[[self
client]
URLProtocol:self
didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self
client]
URLProtocol:self
didLoadData:data];
[[self
client]
URLProtocolDidFinishLoading:self];
}
else
{
self.connection
=
[NSURLConnection
connectionWithRequest:mutableReqeust
delegate:self];
}
}
-
(void)stopLoading
{
if
(self.connection
!=
nil)
{
[self.connection
cancel];
self.connection
=
nil;
}
}
-
(NSString
*)getMIMETypeWithCAPIAtFilePath:(NSString
*)path
{
if
(![[[NSFileManager
alloc]
init]
fileExistsAtPath:path])
{
return
nil;
}
CFStringRef
UTI
=
UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(__bridge
CFStringRef)[path
pathExtension],
NULL);
CFStringRef
MIMEType
=
UTTypeCopyPreferredTagWithClass
(UTI,
kUTTagClassMIMEType);
CFRelease(UTI);
if
(!MIMEType)
{
return
@"application/octet-stream";
}
return
(__bridge
NSString
*)(MIMEType);
}
#pragma
mark
-
拼接響應(yīng)Response
-
(NSHTTPURLResponse
*)jointResponseWithData:(NSData
*)data
dataLength:(NSInteger)dataLength
mimeType:(NSString
*)mimeType
requestUrl:(NSURL
*)requestUrl
statusCode:(NSInteger)statusCode
httpVersion:(NSString
*)httpVersion
{
NSDictionary
*dict
=
@{@"Content-type":mimeType,
@"Content-length":[NSString
stringWithFormat:@"%ld",dataLength]};
NSHTTPURLResponse
*response
=
[[NSHTTPURLResponse
alloc]
initWithURL:requestUrl
statusCode:statusCode
HTTPVersion:httpVersion
headerFields:dict];
return
response;
}
#pragma
mark-
NSURLConnectionDelegate
-
(void)connection:(NSURLConnection
*)connection
didFailWithError:(NSError
*)error
{
[self.client
URLProtocol:self
didFailWithError:error];
}
#pragma
mark
-
NSURLConnectionDataDelegate
-
(void)connection:(NSURLConnection
*)connection
didReceiveResponse:(NSURLResponse
*)response
{
self.responseData
=
[[NSMutableData
alloc]
init];
[self.client
URLProtocol:self
didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
-
(void)connection:(NSURLConnection
*)connection
didReceiveData:(NSData
*)data
{
[
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 歷年課題申報書查看
- 銅鼓文化課題項目申報書
- 高校 工會課題申報書
- 體育課題申報評審書范文
- 合作投資酒店意向合同范本
- 人防車位產(chǎn)權(quán)合同范本
- 單價工裝采購合同范本
- 合同范本可以代替律師證
- 少數(shù)民族文化課題申報書
- 不交金合同范本
- 2025年深圳市高三一模英語試卷答案詳解講評課件
- 2025年黑龍江民族職業(yè)學(xué)院單招職業(yè)技能測試題庫附答案
- 2025年黑龍江旅游職業(yè)技術(shù)學(xué)院單招職業(yè)適應(yīng)性測試題庫一套
- 年產(chǎn)60萬噸摻混肥項目可行性研究報告申請立項
- 2025年2月《公共安全視頻圖像信息系統(tǒng)管理條例》學(xué)習(xí)解讀課件
- 2025年江西青年職業(yè)學(xué)院高職單招職業(yè)技能測試近5年??及鎱⒖碱}庫含答案解析
- 全套教學(xué)課件《工程倫理學(xué)》
- 江蘇省建筑與裝飾工程計價定額(2014)電子表格版
- 2024年山東經(jīng)貿(mào)職業(yè)學(xué)院高職單招(英語/數(shù)學(xué)/語文)筆試歷年參考題庫含答案解析
- 初中物理校本教材《物理之窗》內(nèi)容
- 清華大學(xué)考生自述
評論
0/150
提交評論