【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析_第1頁
【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析_第2頁
【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析_第3頁
【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析_第4頁
【移動應(yīng)用開發(fā)技術(shù)】ios中wkwebview離線化加載h5資源的示例分析_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論