Detect when a webview video becomes fullscreen on ios8

后端 未结 5 1804
生来不讨喜
生来不讨喜 2020-12-05 11:48

I have an app where users can open videos from UIWebview, including Youtube ones. In iOS7, I was able to get a notification when it started playing, or when it became full s

5条回答
  •  误落风尘
    2020-12-05 12:03

    @NorthBlast's answer works well for detecting any UIWindow appearing on top of the UIViewController that holds the UIWebView. Unfortunately, it's hard to filter what kind of UIWindow is (since, well... you can't really know if it is a video or some other kind of window).

    There are 3 special cases I prefer to filter, in which you're sure they are NOT video player windows, those are:

    1) _UIAlertControllerShimPresenterWindow, which is a kind of window that appears when using alerts (like UIAlertView).

    2) UITextEffectsWindow, which appears when presenting special iOS windows (like the share window, UIActivityViewController).

    3) UIRemoteKeyboardWindow which appears when presenting the keyboard (for some reason, this class only appeared to me when using Swift, but on Objective-C it didn't... no clue why is that).

    So to subscribe to notifications, I use (just like @NorthBlast said):

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowDidBecomeActive:)
                                                 name:UIWindowDidBecomeVisibleNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowDidBecomeHidden:)
                                                 name:UIWindowDidBecomeHiddenNotification
                                               object:nil];
    

    Then the implementations:

    - (void)windowDidBecomeActive:(NSNotification *)notification {
        if ( [self isVideoPlayerWindow:notification.object] ) {
            // Do what's needed if it is a video
            // For example, on a live streaming radio app, I would stop the audio if a video is started
        }
    }
    
    - (void)windowDidBecomeHidden:(NSNotification *)notification {
        if ( [self isVideoPlayerWindow:notification.object] ) {
            // Do what's needed if it is a video
        }
    }
    
    - (BOOL)isVideoPlayerWindow:(id)notificationObject {
        /*
         Define non video classes here, add more if you need it
        */
        static NSArray *nonVideoClasses = @[
            @"_UIAlertControllerShimPresenterWindow",
            @"UITextEffectsWindow",
            @"UIRemoteKeyboardWindow"
        ];
    
        BOOL isVideo = YES;
        for ( NSString *testClass in nonVideoClasses ) {
            isVideo = isVideo && ! [notificationObject isKindOfClass:NSClassFromString(testClass)];
        }
    
        return isVideo;
    }
    

提交回复
热议问题