在混合開發(fā)中,難免會遇到需要服務器判斷是否為app打開該網(wǎng)頁
可以通過設置webview的userAgent實現(xiàn)判斷
- 如果多個webView共有一個父類的話推薦使用:
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSLog(@"%@", result);
}];
這一種不使用Block,適合多個webView共用一個父類
- 使用Block,注意block內(nèi)的執(zhí)行順序
self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
__weak typeof(self) weakSelf = self;
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
NSString *userAgent = result;
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
strongSelf.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
// After this point the web view will use a custom appended user agent
[strongSelf.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSLog(@"%@", result);
}];
}];