iOS中WebView的一些使用
阿新 • • 發佈:2019-02-10
返回按鈕
在web頁面中,可能存在多級跳轉的問題,但是預設的返回按鈕會返回原生頁面的上級頁面,這個時候,我們通常需要做一下處理(程式碼:)
if ([_mainWebView canGoBack]) {//判斷是否存在web頁面的返回
[_mainWebView goBack];
//用延遲處理的方式重新整理webview(非延遲重新整理會出現一些問題)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue() , ^{
[_mainWebView reload];
});
web頁面和js的互動:
web頁面和js有三種互動方式,協議互動,連結互動和代理互動,協議互動和連結互動其實可以看做是一個東西都是在- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType這個方法裡面進行處理
例如:
NSString *requestString = [[request URL] absoluteString];
NSLog (@"requestString = %@",requestString);
if ([requestString rangeOfString:@"/account"].location != NSNotFound){
[self.navigationController popViewControllerAnimated:YES];
}
都是判斷連線中是否含有某段特殊字元,然後進行對應的操作
但是往往實際操作過程中,我們會使用到更多的東西,比如說,在現有的很多專案的積分商城中,涉及到的登入問題,如何使用js呼叫登入,並且在登入之後跳轉到對應的web頁面,以及傳遞引數
這個時候我們就要使用代理的方式進行互動,例如:
@protocol JSObjcDelegate <JSExport>
//定義一個互動方法
- (void)jsMakeAppLogIn:(NSString *)urlString;
@end
在下面這個方法裡面做處理
- (void)webViewDidFinishLoad:(UIWebView *)webView{
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSLog(@"%@",context);
context.exceptionHandler = ^(JSContext *con, JSValue *exception) {
NSLog(@"%@", exception);
con.exception = exception;
};
//h5裡面的程式碼格式為xx.xxxx(xx為字首,xxxx為方法名)
context[@"字首"] = self;
context[@"方法名"] = ^{
NSArray *arg = [JSContext currentArguments];
for (id obj in arg) {
NSLog(@"引數 === %@", obj);
_getUrlValue = [NSString stringWithFormat:@"%@",obj];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self jsMakeAppLogIn:_getUrlValue];
});
};
}
web頁面的快取清理
清理快取和cookie程式碼
- (void)cleanCacheAndCookie{
//清除cookies
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}
//清除UIWebView的快取
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
}
開啟webview的方式
web頁面的開啟同樣分為POST開啟和Get開啟方式
關於Get的開啟方式就不介紹了,主要介紹一下POST開啟方式
[_mainWebView loadRequest:[self openUrlWithPostMethod:_urlStr params:_paraDic]];
//POST方法編碼URL和引數
- (NSMutableURLRequest *)openUrlWithPostMethod:(NSString*)url params:(NSDictionary*)params
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = @"POST";
NSMutableString *paramStr = [NSMutableString string];
[params enumerateKeysAndObjectsUsingBlock:^( id key , id value , BOOL *stop ) {
if( paramStr.length > 0 ){
[paramStr appendString:@"&"];
}
if ([key isEqualToString:@"url"]) {
}else
[paramStr appendFormat:@"%@=%@",[self encodeString:key],[self encodeString:value]];
*stop = NO;
}];
NSLog(@"%@ params ==== %@",request.URL,params);
request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
return request;
}
-(NSString*)encodeString:(NSString*)unencodedString{
NSString *encodedString = (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
return encodedString;
}
web頁面的App瀏覽器標記
-(void)setUserAgentForMyApp
{
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newUagent = [NSString stringWithFormat:@"%@/特殊標記欄位",secretAgent];
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newUagent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
webView = nil;
}
web頁面的放大縮小(捏合手勢)
_mainWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
_mainWebView.scalesPageToFit=YES;
_mainWebView.multipleTouchEnabled=YES;
暫時先介紹這些具有代表性的