您的位置:首页 > 移动开发

iOS_WKWebView加载本地网页

2017-11-03 15:27 731 查看
@property (strong, nonatomic) WKWebView *webView;
@property (nonatomic, copy) NSString *url;


WKWebView
加载工程内
Html
页面

// 我这里是将html资源文件放置在工程内一个bundle的文件夹内
NSString *path = [[[NSBundle mainBundle] pathForResource:@"H5Local" ofType:@"bundle"] stringByAppendingPathComponent:@"fund/index.html"];
// 拼接后的网页路径
self.url = [self componentFileUrlWithOriginFilePath:path Dictionary:@{@"key":@"value"}];
// 加载网页
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];


WKWebView
加载沙盒内
Html
页面

// 将要加载的html路径
NSString *urlStr1 = @"~/Cache/fund/index.html";
// 将要加载的html路径的上一层级路径
NSString *urlStr2 = @"~/Cache/fund";
self.url = [self componentFileUrlWithOriginFilePath:urlStr1 Dictionary:@{@"key":@"value"}];

[self.webView loadFileURL:[NSURL URLWithString:self.url] allowingReadAccessToURL:[NSURL fileURLWithPath:urlStr2]];


WKWebView
对加载的本地网页进行后拼接参数

无论是加载沙盒内网页还是工程内网页,如果需要在网页后拼接参数,不能简单的使用字符串拼接的方式进行拼接,需要借助
NSURLComponents
类进行数据的拼接。

使用方法如下:

/**
本地网页数据拼接

@param filePath 网页路径
@param dictionary 拼接的参数
@return 拼接后网页路径字符串
*/
- (NSString *)componentFileUrlWithOriginFilePath:(NSString *)filePath Dictionary:(NSDictionary *)dictionary{
NSURL *url = [NSURL fileURLWithPath:filePath isDirectory:NO];
// NO代表此路径没有下一级,等同于[NSURL fileURLWithPath:filePath];
// 如果设置为YES,则路径会自动添加一个“/”
NSURLComponents *urlComponents = [[NSURLComponents alloc]initWithURL:url resolvingAgainstBaseURL:NO];
NSMutableArray *mutArray = [NSMutableArray array];
for (NSString *key in dictionary.allKeys) {
NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:key value:dictionary[key]];
[mutArray addObject:item];
}
[urlComponents setQueryItems:mutArray];
// urlComponents.URL  返回拼接后的(NSURL *)
// urlComponents.string 返回拼接后的(NSString *)
return urlComponents.string;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios html