I had the same problem, and resolved it using WKWebView
instead of UIWebView
. This new implementation for showing web content is the one recommended by Apple, as it seems that UIWebView is going to be deprecated.
One thing about this new object, is that the method for evaluating a JavaScript is asynchronous. Therefore, if you want to use a synchronous method to fetch the userAgent, you should create your own category of WKWebView as explained here.
The code should be something like this
@interface WKWebView(SynchronousEvaluateJavaScript)
- (NSString *)stringByEvaluatingJavaScript:(NSString *)script;
@end
@implementation WKWebView(SynchronousEvaluateJavaScript)
- (NSString *)stringByEvaluatingJavaScript:(NSString *)script
{
__block NSString *resultString = nil;
[self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
if (error == nil) {
if (result != nil) {
resultString = [NSString stringWithFormat:@"%@", result];
}
} else {
NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
}
}];
while (resultString == nil)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return resultString;
}
@end
And the invocation is quite the same than before:
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero];
defaultUserAgent = [webView stringByEvaluatingJavaScript:@"navigator.userAgent"];