Search code examples
javascriptiosuiwebvieworientationobserver-pattern

OrientationObserver in UIWebView


I have the following structure

UIViewController1 --> UIWebView

I run a local HTML File in WebView from Documents-Folder. Within the HTML I have a short JavaScript snippet, which checks the interface Orientation via orientationObserver.

The UIViewController1 is locked to landscape.

OrientationObserver always returns "portrait", should return "landscape". I don't know what causes the wrong return value.

What could cause the orientationObserver to return the wrong orientation in this constellation ?

I'm really stuck here, and I need to get the right orientation returned.

Any help is appreciated.


Solution

  • Finally, after four days of banging my head against the iMac i found a solution for this.

    In UIWebView there is no window.orientation available (i wonder why!?). If a JavaScript request the value, it gets "0" what means the orientation is "portrait".

    You can go around the problem if you add the "orientation" Setter to the window.

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)req navigationType:(UIWebViewNavigationType)navigationType {
    
        [webView stringByEvaluatingJavaScriptFromString:@"window.__defineGetter__('orientation', function(){return 90;});"];
    
    return YES; 
    }
    

    This implements a getter within window and the JavaScript get's the return value. If you want your app to respond to interface orientation changes, you can set the values in the delegates again to the correct values (-90, 0, 90 or 180).