iOS 自定义设置wkwebview的 userAgent

135 阅读1分钟

NSString *newAgent = @" Theatre"; WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init]; webViewConfig.allowsInlineMediaPlayback = YES; NSString *userAgent = webViewConfig.applicationNameForUserAgent; userAgent = [userAgent stringByAppendingString:@"myapp/1.0.0"]; webViewConfig.applicationNameForUserAgent = userAgent; [self.dwebview evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) { if (error) { NSLog(@"UA: Error == %@", error.localizedDescription); } else { NSLog(@"userAgent == %@", result); NSString *userAgent=result; NSString *newUserAgent = [userAgent stringByAppendingString:newAgent]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; [[NSUserDefaults standardUserDefaults] synchronize];

        if (ISIPHONE) {
            
        }else{
            [self.dwebview setCustomUserAgent:newUserAgent];
        }
        if (@available(iOS 9.0, *)) {
                 [self.dwebview setCustomUserAgent:newUserAgent];
             } else {
                 [self.dwebview setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
              }
    }
    NSString *urlString =self.apiLinkURL;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [self.dwebview loadRequest:request];

}];