Cordova中iOS端访问远程web链接调用Cordova插件

首先感谢假装程序猿的文章

最近项目采用cordova框架开发,所以就苦了前端同学,稍微改动都要Jenkins去打包,所以在想能不能直接访问前端同学本地链接,改完直接就能生效那种,下面开始。


1.修改config.xml文件

在config.xml文件中添加以下代码:




说明:后面两个属性是允许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的路径替换为

http://injection/cordova.js

3.添加CDVURLProtocolCustom

这个类的作用是拦截web发出的请求,将第二步中的

http://injection/cordova.js

拦截,之后跳转本地cordova.js。

CDVURLProtocolCustom.h

#import 
#import 

@interface CDVURLProtocolCustom : NSURLProtocol

@end

CDVURLProtocolCustom.m

#import "CDVURLProtocolCustom.h"
#import 

@interface CDVURLProtocolCustom ()

@end

NSString* const kCDVAssetsLibraryPrefixes = @"http://injection/cordova.js";

@implementation CDVURLProtocolCustom

// 这个方法用来拦截H5页面请求
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
{
    NSURL* theUrl = [theRequest URL];
    
    // 判断是否是我们定义的url,若是,返回YES,继续执行其他方法,若不是,返回NO,不执行其他方法
    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以后,会执行该方法,完成替换资源并返回给H5页面
- (void)startLoading
{
    // NSLog(@"%@ received %@ - start", self, NSStringFromSelector(_cmd));
    NSString* url=super.request.URL.resourceSpecifier;
    NSString* cordova = [url stringByReplacingOccurrencesOfString:@"//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
Q1.png

解决:将CDVURLProtocolCustom移动到Public文件夹下,与CDVAppdelegate同级即可,删除plugins下的文件,如下图所示。


Q2.png
Q3.png

编译成功,希望遇到同样问题的同学可以避免。

你可能感兴趣的:(Cordova中iOS端访问远程web链接调用Cordova插件)