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

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

最近项目采用cordova框架开发,所以就苦了前端同学,稍微改动都要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的路径替换为

http://injection/cordova.js

3.添加CDVURLProtocolCustom

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

http://injection/cordova.js

拦截,之后跳转本地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,继续执行其他方法,若不是,返回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 foundQ1解决:将CDVURLProtocolCustom移动到Public文件夹下,与CDVAppdelegate同级即可,删除plugins下的文件,如下图所示。
Q2

Q3

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值