Browse Source

refactoring

Signed-off-by: marinofaggiana <marino@marinofaggiana.com>
marinofaggiana 3 years ago
parent
commit
0e89d50949

+ 0 - 7
iOSClient/AppDelegate.swift

@@ -64,13 +64,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     var shares: [tableShare] = []
     var timerErrorNetworking: Timer?
     
-    var player: AVPlayer?
-    var commandCenterPlayCommand: Any?
-    var commandCenterPauseCommand: Any?
-    var commandCenterSkipForwardCommand: Any?
-    var commandCenterSkipBackwardCommand: Any?
-    var commandCenterChangePlaybackPositionCommand: Any?
-
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         
         let userAgent = CCUtility.getUserAgent() as String

+ 25 - 23
iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift

@@ -41,6 +41,7 @@ class NCPlayer: NSObject {
     private var observerAVPlayerItemDidPlayToEndTime: Any?
     private var timeObserver: Any?
 
+    public var player: AVPlayer?
     public var durationTime: CMTime = .zero
     public var metadata: tableMetadata?
     public var videoLayer: AVPlayerLayer?
@@ -65,23 +66,23 @@ class NCPlayer: NSObject {
         }
         
         print("Play URL: \(url)")
-        appDelegate.player = AVPlayer(url: url)
+        player = AVPlayer(url: url)
         
         if metadata.livePhoto {
-            appDelegate.player?.isMuted = false
+            player?.isMuted = false
         } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
-            appDelegate.player?.isMuted = CCUtility.getAudioMute()
+            player?.isMuted = CCUtility.getAudioMute()
         } else {
-            appDelegate.player?.isMuted = CCUtility.getAudioMute()
+            player?.isMuted = CCUtility.getAudioMute()
             if let time = NCManageDatabase.shared.getVideoTime(metadata: metadata) {
                 timeSeek = time
             }
         }
-        appDelegate.player?.seek(to: timeSeek)
+        player?.seek(to: timeSeek)
         
         // At end go back to start & show toolbar
-        observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: appDelegate.player?.currentItem, queue: .main) { (notification) in
-            if let item = notification.object as? AVPlayerItem, let currentItem = self.appDelegate.player?.currentItem, item == currentItem {
+        observerAVPlayerItemDidPlayToEndTime = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main) { (notification) in
+            if let item = notification.object as? AVPlayerItem, let currentItem = self.player?.currentItem, item == currentItem {
                 NCKTVHTTPCache.shared.saveCache(metadata: metadata)
                 self.videoSeek(time: .zero)
                 if !(detailView?.isShow() ?? false) {
@@ -91,22 +92,22 @@ class NCPlayer: NSObject {
             }
         }
         
-        timeObserver = appDelegate.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
-            if self.appDelegate.player?.currentItem?.status == .readyToPlay {
+        timeObserver = player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main, using: { (CMTime) in
+            if self.player?.currentItem?.status == .readyToPlay {
                 self.playerToolBar?.updateToolBar()
             }
         })
         
-        appDelegate.player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
+        player?.currentItem?.asset.loadValuesAsynchronously(forKeys: ["playable"], completionHandler: {
             var error: NSError? = nil
-            let status = self.appDelegate.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error)
+            let status = self.player?.currentItem?.asset.statusOfValue(forKey: "playable", error: &error)
             switch status {
             case .loaded:
                 DispatchQueue.main.async {
                     if let imageVideoContainer = imageVideoContainer {
                         
                         self.imageVideoContainer = imageVideoContainer
-                        self.videoLayer = AVPlayerLayer(player: self.appDelegate.player)
+                        self.videoLayer = AVPlayerLayer(player: self.player)
                         self.videoLayer!.frame = imageVideoContainer.bounds
                         self.videoLayer!.videoGravity = .resizeAspect
                         
@@ -129,7 +130,7 @@ class NCPlayer: NSObject {
                         }
                     }
                     
-                    self.durationTime = self.appDelegate.player?.currentItem?.asset.duration ?? .zero
+                    self.durationTime = self.player?.currentItem?.asset.duration ?? .zero
                     NCManageDatabase.shared.addVideoTime(metadata: metadata, time: nil, durationTime: self.durationTime)
                     
                     self.playerToolBar?.setBarPlayer(ncplayer: self, timeSeek: timeSeek, metadata: metadata, image: imageVideoContainer?.image)
@@ -177,19 +178,20 @@ class NCPlayer: NSObject {
     
     func videoRemoved() {
 
-        playerPause()
+        if isPlay() {
+            playerPause()
+        }
         playerToolBar?.disableCommandCenter()
 
         if let observerAVPlayerItemDidPlayToEndTime = self.observerAVPlayerItemDidPlayToEndTime {
             NotificationCenter.default.removeObserver(observerAVPlayerItemDidPlayToEndTime)
         }
         if  let timeObserver = self.timeObserver {
-            appDelegate.player?.removeTimeObserver(timeObserver)
+            player?.removeTimeObserver(timeObserver)
         }
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil)
         
         self.videoLayer?.removeFromSuperlayer()
-        
         self.videoLayer = nil
         self.observerAVPlayerItemDidPlayToEndTime = nil
         self.timeObserver = nil
@@ -223,7 +225,7 @@ class NCPlayer: NSObject {
     
     func isPlay() -> Bool {
         
-        if appDelegate.player?.rate == 1 { return true } else { return false }
+        if player?.rate == 1 { return true } else { return false }
     }
     
     func isPictureInPictureActive() -> Bool {
@@ -237,13 +239,13 @@ class NCPlayer: NSObject {
     
     func playerPlay() {
                 
-        appDelegate.player?.play()
+        player?.play()
         self.playerToolBar?.updateToolBar()
     }
     
     func playerPause() {
         
-        appDelegate.player?.pause()
+        player?.pause()
         self.playerToolBar?.updateToolBar()
         
         if let pictureInPictureController = pictureInPictureController, pictureInPictureController.isPictureInPictureActive {
@@ -253,7 +255,7 @@ class NCPlayer: NSObject {
     
     func videoSeek(time: CMTime) {
         
-        appDelegate.player?.seek(to: time)
+        player?.seek(to: time)
         self.saveTime(time)
     }
     
@@ -267,20 +269,20 @@ class NCPlayer: NSObject {
     
     func saveCurrentTime() {
         
-        if let player = appDelegate.player {
+        if let player = self.player {
             saveTime(player.currentTime())
         }
     }
     
     @objc func generatorImagePreview() {
-        guard let time = appDelegate.player?.currentTime() else { return }
+        guard let time = player?.currentTime() else { return }
         guard let metadata = self.metadata else { return }
         if metadata.livePhoto { return }
         if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
 
         var image: UIImage?
 
-        if let asset = appDelegate.player?.currentItem?.asset {
+        if let asset = player?.currentItem?.asset {
 
             do {
                 let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!

+ 27 - 20
iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift

@@ -54,6 +54,13 @@ class NCPlayerToolBar: UIView {
     private var metadata: tableMetadata?
     private var image: UIImage?
     
+    var commandCenterPlayCommand: Any?
+    var commandCenterPauseCommand: Any?
+    var commandCenterSkipForwardCommand: Any?
+    var commandCenterSkipBackwardCommand: Any?
+    var commandCenterChangePlaybackPositionCommand: Any?
+
+    
     // MARK: - View Life Cycle
 
     override func awakeFromNib() {
@@ -179,7 +186,7 @@ class NCPlayerToolBar: UIView {
         if timeSeek != nil {
             time = timeSeek!
         } else {
-            time = (appDelegate.player?.currentTime() ?? .zero).convertScale(1000, method: .default)
+            time = (ncplayer.player?.currentTime() ?? .zero).convertScale(1000, method: .default)
             
         }
         playbackSlider.value = Float(time.seconds)
@@ -228,7 +235,7 @@ class NCPlayerToolBar: UIView {
         var nowPlayingInfo = [String : Any]()
 
         // Add handler for Play Command
-        appDelegate.commandCenterPlayCommand = MPRemoteCommandCenter.shared().playCommand.addTarget { event in
+        commandCenterPlayCommand = MPRemoteCommandCenter.shared().playCommand.addTarget { event in
             
             if !ncplayer.isPlay() {
                 ncplayer.playerPlay()
@@ -238,7 +245,7 @@ class NCPlayerToolBar: UIView {
         }
       
         // Add handler for Pause Command
-        appDelegate.commandCenterPauseCommand = MPRemoteCommandCenter.shared().pauseCommand.addTarget { event in
+        commandCenterPauseCommand = MPRemoteCommandCenter.shared().pauseCommand.addTarget { event in
           
             if ncplayer.isPlay() {
                 ncplayer.playerPause()
@@ -248,7 +255,7 @@ class NCPlayerToolBar: UIView {
         }
         
         // Add handler for Backward Command
-        appDelegate.commandCenterSkipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
+        commandCenterSkipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
             
             let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
             self.skip(seconds: -seconds)
@@ -256,7 +263,7 @@ class NCPlayerToolBar: UIView {
         }
             
         // Add handler for Forward Command
-        appDelegate.commandCenterSkipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
+        commandCenterSkipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
             
             let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
             self.skip(seconds: seconds)
@@ -264,7 +271,7 @@ class NCPlayerToolBar: UIView {
         }
         
         nowPlayingInfo[MPMediaItemPropertyTitle] = metadata?.fileNameView
-        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = appDelegate.player?.currentItem?.asset.duration.seconds
+        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = ncplayer.player?.currentItem?.asset.duration.seconds
         if let image = self.image {
             nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
                 return image
@@ -278,21 +285,21 @@ class NCPlayerToolBar: UIView {
         UIApplication.shared.endReceivingRemoteControlEvents()
         MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
 
-        if let playCommand = appDelegate.commandCenterPlayCommand {
+        if let playCommand = self.commandCenterPlayCommand {
             MPRemoteCommandCenter.shared().playCommand.removeTarget(playCommand)
-            appDelegate.commandCenterPlayCommand = nil
+            self.commandCenterPlayCommand = nil
         }
-        if let pauseCommand = appDelegate.commandCenterPauseCommand {
+        if let pauseCommand = self.commandCenterPauseCommand {
             MPRemoteCommandCenter.shared().pauseCommand.removeTarget(pauseCommand)
-            appDelegate.commandCenterPauseCommand = nil
+            self.commandCenterPauseCommand = nil
         }
-        if let commandCenterSkipBackwardCommand = appDelegate.commandCenterSkipBackwardCommand {
+        if let commandCenterSkipBackwardCommand = self.commandCenterSkipBackwardCommand {
             MPRemoteCommandCenter.shared().previousTrackCommand.removeTarget(commandCenterSkipBackwardCommand)
-            appDelegate.commandCenterSkipBackwardCommand = nil
+            self.commandCenterSkipBackwardCommand = nil
         }
-        if let commandCenterSkipForwardCommand = appDelegate.commandCenterSkipForwardCommand {
+        if let commandCenterSkipForwardCommand = self.commandCenterSkipForwardCommand {
             MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(commandCenterSkipForwardCommand)
-            appDelegate.commandCenterSkipForwardCommand = nil
+            self.commandCenterSkipForwardCommand = nil
         }
     }
     
@@ -407,7 +414,7 @@ class NCPlayerToolBar: UIView {
     
     func skip(seconds: Float64) {
         guard let ncplayer = ncplayer else { return }
-        guard let player = appDelegate.player else { return }
+        guard let player = ncplayer.player else { return }
         
         let currentTime = player.currentTime()
         var newTime: CMTime = .zero
@@ -476,16 +483,16 @@ class NCPlayerToolBar: UIView {
     
     @IBAction func playerPause(_ sender: Any) {
         
-        if appDelegate.player?.timeControlStatus == .playing {
+        if ncplayer?.player?.timeControlStatus == .playing {
             ncplayer?.playerPause()
             ncplayer?.saveCurrentTime()
             timerAutoHide?.invalidate()
-        } else if appDelegate.player?.timeControlStatus == .paused {
+        } else if ncplayer?.player?.timeControlStatus == .paused {
             ncplayer?.playerPlay()
             startTimerAutoHide()
-        } else if appDelegate.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
+        } else if ncplayer?.player?.timeControlStatus == .waitingToPlayAtSpecifiedRate {
             print("timeControlStatus.waitingToPlayAtSpecifiedRate")
-            if let reason = appDelegate.player?.reasonForWaitingToPlay {
+            if let reason = ncplayer?.player?.reasonForWaitingToPlay {
                 switch reason {
                 case .evaluatingBufferingRate:
                     print("reasonForWaitingToPlay.evaluatingBufferingRate")
@@ -505,7 +512,7 @@ class NCPlayerToolBar: UIView {
         let mute = CCUtility.getAudioMute()
         
         CCUtility.setAudioMute(!mute)
-        appDelegate.player?.isMuted = !mute
+        ncplayer?.player?.isMuted = !mute
         updateToolBar()
         reStartTimerAutoHide()
     }

+ 4 - 9
iOSClient/Viewer/NCViewerMedia/NCViewerMediaZoom.swift

@@ -136,9 +136,6 @@ class NCViewerMediaZoom: UIViewController {
             viewerMedia?.textColor = NCBrandColor.shared.label
             viewerMedia?.progressView.isHidden = false
         }
-        
-        NotificationCenter.default.addObserver(self, selector: #selector(openDetail(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
-
     }
     
     override func viewDidAppear(_ animated: Bool) {
@@ -152,18 +149,16 @@ class NCViewerMediaZoom: UIViewController {
         
         // DOWNLOAD
         downloadFile()
-    }
-    
-    override func viewWillDisappear(_ animated: Bool) {
-        super.viewWillDisappear(animated)
         
-        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
+        NotificationCenter.default.addObserver(self, selector: #selector(openDetail(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
     }
     
     override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
         
         self.ncplayer?.videoRemoved()
+        
+        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
     }
     
     override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
@@ -335,7 +330,7 @@ extension NCViewerMediaZoom {
         }
         
         scrollView.pinchGestureRecognizer?.isEnabled = true
-        if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && !metadata.livePhoto && appDelegate.player?.timeControlStatus == .paused {
+        if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && !metadata.livePhoto && ncplayer?.player?.timeControlStatus == .paused {
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
         }
     }