需求:
1、投射airplay后,有些页面或播放状态没有权限投射时,需要修改第二屏内容;
2、游戏时airplay后,iPhone当成手柄使用;
原来:
获取第二屏幕信息--->创建一个新的Window--->将新的Window对应的Screen屏幕设置为第二屏幕--->设置新的屏幕的UI显示。
获取第二屏幕信息
@discardableResult public func connectExternalScreen() -> Bool{
if UIScreen.screens.count > 1 {
for screen in UIScreen.screens {
if screen != UIScreen.main {//获取第二屏幕信息
self.didConnectExternalScreen(externalScreen: screen)
return true
}
}
}
return false
}
创建一个新的Window--->将新的Window对应的Screen屏幕设置为第二屏幕--->设置新的屏幕的UI显示。
fileprivate func didConnectExternalScreen(externalScreen: UIScreen) {
if externalViewController == nil {//设置新的屏幕的UI显示。
let viewController = UIViewController()
externalViewController = viewController
}
if externalWindow == nil {
let window = UIWindow(frame: externalScreen.bounds)//创建一个新的Window
externalWindow = window
externalWindow?.rootViewController = externalViewController
externalWindow?.isHidden = false
}
externalScreenStatus = .connected
externalWindow?.screen = externalScreen//将新的Window对应的Screen屏幕设置为第二屏幕
NotificationCenter.default.post(name: NSNotification.Name.ExternalScreenDidConnected, object: nil)
}
第二屏的状态监听:
extension ExternalScreenManager {
public func beginObserveExternalScreen() {
connectExternalScreen()
NotificationCenter.default.addObserver(self, selector: #selector(self.externalScreenDidConnect(_:)), name: NSNotification.Name.UIScreenDidConnect, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.externalScreenDidDisconnect(_:)), name: NSNotification.Name.UIScreenDidDisconnect, object: nil)
}
public func stopObserveExternalScreen() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIScreenDidConnect, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIScreenDidDisconnect, object: nil)
}
@objc func externalScreenDidConnect(_ notifiaction:NSNotification) {
let screen:UIScreen = notifiaction.object as! UIScreen
self.didConnectExternalScreen(externalScreen: screen)
}
@objc func externalScreenDidDisconnect(_ notifiaction:NSNotification) {
let screen:UIScreen = notifiaction.object as! UIScreen
self.didDisconnectScrren(externalScreen: screen)
}
}