首先感謝假裝程序猿的文章
最近項目采用cordova框架開發(fā)甚脉,所以就苦了前端同學滚澜,稍微改動都要Jenkins去打包蓉媳,所以在想能不能直接訪問前端同學本地鏈接八酒,改完直接就能生效那種空民,下面開始。
1.修改config.xml文件
在config.xml文件中添加以下代碼:
<content src="http://192.168.18.126:8081/#/" />
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
說明:后面兩個屬性是允許APP加載外部鏈接羞迷,不加的話會直接跳轉瀏覽器訪問界轩。
2.修改訪問的index.html代碼
var script = document.createElement('script');
script.type = "text/javascript";
script.src="http://injection/cordova.js";
document.getElementsByTagName('body')[0].appendChild(script);
說明:這段代碼要添加在所有js文件加載完之后,因為cordova不允許web直接訪問"file://"開頭的鏈接衔瓮,所以需要前端文件將cordova.js的路徑替換為
3.添加CDVURLProtocolCustom
這個類的作用是攔截web發(fā)出的請求浊猾,將第二步中的
攔截,之后跳轉本地cordova.js热鞍。
CDVURLProtocolCustom.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CDVURLProtocolCustom : NSURLProtocol
@end
CDVURLProtocolCustom.m
#import "CDVURLProtocolCustom.h"
#import <CoreServices/CoreServices.h>
@interface CDVURLProtocolCustom ()
@end
NSString* const kCDVAssetsLibraryPrefixes = @"http://injection/cordova.js";
@implementation CDVURLProtocolCustom
// 這個方法用來攔截H5頁面請求
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
{
NSURL* theUrl = [theRequest URL];
// 判斷是否是我們定義的url葫慎,若是,返回YES薇宠,繼續(xù)執(zhí)行其他方法偷办,若不是,返回NO澄港,不執(zhí)行其他方法
if ([[theUrl absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request
{
// NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));
return request;
}
// 獲取本地文件路徑
- (NSString*)pathForResource:(NSString*)resourcepath
{
NSBundle* mainBundle = [NSBundle mainBundle];
NSMutableArray* directoryParts = [NSMutableArray arrayWithArray:[resourcepath componentsSeparatedByString:@"/"]];
NSString* filename = [directoryParts lastObject];
[directoryParts removeLastObject];
NSString* directoryPartsJoined = [directoryParts componentsJoinedByString:@"/"];
NSString* directoryStr = @"www";
if ([directoryPartsJoined length] > 0) {
directoryStr = [NSString stringWithFormat:@"%@/%@", directoryStr, [directoryParts componentsJoinedByString:@"/"]];
}
return [mainBundle pathForResource:filename ofType:@"" inDirectory:directoryStr];
}
// 在canInitWithRequest方法返回YES以后椒涯,會執(zhí)行該方法,完成替換資源并返回給H5頁面
- (void)startLoading
{
// NSLog(@"%@ received %@ - start", self, NSStringFromSelector(_cmd));
NSString* url=super.request.URL.resourceSpecifier;
NSString* cordova = [url stringByReplacingOccurrencesOfString:@"http://injection/" withString:@""];
NSURL* startURL = [NSURL URLWithString:cordova];
NSString* cordovaFilePath =[self pathForResource:[startURL path]];
if (!cordovaFilePath) {
[self sendResponseWithResponseCode:401 data:nil mimeType:nil];//重要
return;
}
CFStringRef pathExtension = (__bridge_retained CFStringRef)[cordovaFilePath pathExtension];
CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
CFRelease(pathExtension);
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
if (type != NULL)
CFRelease(type);
// NSURLResponse *response = [[NSURLResponse alloc] initWithURL:super.request.URL MIMEType:mimeType expectedContentLength:-1 textEncodingName:nil];
NSData* data = [NSData dataWithContentsOfFile:cordovaFilePath];
[self sendResponseWithResponseCode:200 data:data mimeType:mimeType];
}
- (void)stopLoading
{
// do any cleanup here
}
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB
{
return NO;
}
// 將本地資源返回給H5頁面
- (void)sendResponseWithResponseCode:(NSInteger)statusCode data:(NSData*)data mimeType:(NSString*)mimeType
{
if (mimeType == nil) {
mimeType = @"text/plain";
}
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:statusCode HTTPVersion:@"HTTP/1.1" headerFields:@{@"Content-Type" : mimeType}];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
if (data != nil) {
[[self client] URLProtocol:self didLoadData:data];
}
[[self client] URLProtocolDidFinishLoading:self];
}
@end
4.初始化CDVURLProtocolCustom
在CDVAppdelegate的application:(UIApplication*)application didFinishLaunchingWithOptions:方法中添加
[NSURLProtocol registerClass:[CDVURLProtocolCustom class]]慢睡;
5.遇到問題
Q:'CDVURLProtocolCustom.h' file not found解決:將CDVURLProtocolCustom移動到Public文件夾下逐工,與CDVAppdelegate同級即可,刪除plugins下的文件漂辐,如下圖所示泪喊。
編譯成功,希望遇到同樣問題的同學可以避免髓涯。