13
votes

I want to find out userAgent of current browser in iOS.

So in default project created by Xcode I added:

#import "ViewController.h"
#import <WebKit/WKWebView.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    dispatch_async(dispatch_get_main_queue(), ^{
        WKWebView *obj = [[WKWebView alloc] initWithFrame:CGRectZero];
        [obj evaluateJavaScript: @"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            NSLog(@"evaluateJavaScript = %@ : %@", result, error);
            NSLog(@"To make sure that webview alive: %@", obj);
        }];
    });
}


@end

it prints what I expect:

evaluateJavaScript = Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 : (null)

but after that it prints:

test4[1930:101220] usage: <WKWebView: 0x7f958f817800; frame = (0 0; 0 0); layer = <CALayer: 0x60000236ed00>>

test4[1930:101220] [assertion] Error acquiring assertion: <Error Domain=RBSAssertionErrorDomain Code=3 "Target is not running or required target entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"Background" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Target is not running or required target entitlement is missing}>

test4[1930:101220] [ProcessSuspension] 0x102dfed00 - ProcessAssertion: Failed to acquire RBS Background assertion 'WebProcess Background Assertion' for process with PID 1933, error: Error Domain=RBSAssertionErrorDomain Code=3 "Target is not running or required target entitlement is missing" UserInfo={RBSAssertionAttribute=<RBSDomainAttribute| domain:"com.apple.webkit" name:"Background" sourceEnvironment:"(null)">, NSLocalizedFailureReason=Target is not running or required target entitlement is missing}

This doesn't look good. Is something wrong with my code, is it possible to avoid these assertions and still get userAgent string?

1
just read the error msg "Target is not running or required target entitlement is missing" which is also correct failure because you can apply a different userAgent string with your own implementation you just did. And you assert javascript before the view did load complete. - Ol Sen
@OlSen how did you conclude all that simply by looking at "Target is not running or required target entitlement is missing"? For me this isn't clear at all. - André Herculano
Hm how did you exactly solve this problem? I have a similar issue: stackoverflow.com/questions/67571345/… - Marcel Schürmann
@MarcelSchürmann Reference to webView should keep alive until completionHandler and destroyed in that handler, so in completionHandler I call dispatch_async and then in main queue I destroy webView. - user1244932

1 Answers

-7
votes

Create an empty UIView and add WKWebView as a subview.