how check table view cell focus and player set pause

how to play video autoplay in uitableviewcell swift
play video in uicollectionviewcell swift github
video player in table view cell ios
play video in uitableviewcell swift 4
play video in uitableviewcell swift github
jp video player swift
play video in uitableviewcell objective-c
video player in uitableview swift

my project

I have several videos in the table in a row.

The problem is that they are played synchronously. On screen 1video and 2video play synchronously

How do i can track focus cell on table view and cell.player?.play(). And other cells cell.player?.pause()

my code:

   class MyViewController
//don't work
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? ListViewCell {
        cell.player?.pause()
    }
}


//don't call
func tableView(_ tableView: UITableView, didUpdateFocusIn context: UITableViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    print("table view cell didUpdateFocusIn")
}




class MyTableviewCell

override func prepareForReuse() {
        super.prepareForReuse()
        player?.pause()
    }

I'm making some changes to your project. Check this https://yadi.sk/d/bQ-eIyMz3VF28V

Decide which video to play or pause when scrolling:

func handleScroll() {
    if let indexPathsForVisibleRows = myTableView.indexPathsForVisibleRows, indexPathsForVisibleRows.count > 0 {
        var focusCell: ListViewCell?

        for indexPath in indexPathsForVisibleRows {
            if let cell = myTableView.cellForRow(at: indexPath) as? ListViewCell {
                if focusCell == nil {
                    let rect = myTableView.rectForRow(at: indexPath)
                    if myTableView.bounds.contains(rect) {
                        cell.player?.play()
                        focusCell = cell
                    } else {
                        cell.player?.pause()
                    }
                } else {
                    cell.player?.pause()
                }
            }
        }
    }
}

Hope this will help you.

ios - how check table view cell focus and player set pause, I'm making some changes to your project. Check this https://yadi.sk/d/bQ-​eIyMz3VF28V. Decide which video to play or pause when scrolling: The cell to give focus to is selected by the cell () method and the cell-selector given to it. If the selected cell is not in the DataTable's current page, the paging will be adjusted to make it visible and the table redrawn. Tables which are disabled ( keys.disable ()) cannot have cells focused.

Use this in Your ViewController

   extension ViewController {
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == #keyPath(UITableView.contentOffset) {
                if let playIndexPath = currentPlayIndexPath {

                    if let cell = tblInstaFeed.cellForRow(at: playIndexPath) {
                        if player.displayView.isFullScreen { return }
                        let visibleCells = tblInstaFeed.visibleCells
                        if visibleCells.contains(cell) {
                      cell.contentView.addSubview(player.displayView)
                            player.displayView.snp.remakeConstraints{
                                $0.edges.equalTo(cell)
                            }
                            self.player.play()
                        } else {
                           player.displayView.removeFromSuperview()
                            self.player.pause()

                        }
                    }
                }
            }
          }
        }

And Call that Like this:

var tableViewContext = 0
    func addTableViewObservers() {
        let options = NSKeyValueObservingOptions([.new, .initial])
        tblInstaFeed?.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: options, context: &tableViewContext)
    }

And Call addTableViewObservers function in viewDidLoad

Hope this will help.

ashish0309/AutoVideoPlayer: Easily Play/Pause videos in , Easily Play/Pause videos in any UIView subclass especially UITableViewCell is in focus, videos can be easily embedded in any UITableViewCell subclass. on background thread and played only when assets are completely downloaded then //set videoURL if you want to show video or else nil } func tableView(_  GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.

You can use indexPathForRow(at: CGpoint)

Here is Extension to tableView

import Foundation
import UIKit

extension UITableView {
      // center point of content size
    var centerPoint : CGPoint {
        get {
            return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
        }
    }

    // center indexPath
     var centerCellIndexPath: IndexPath? {

        if let centerIndexPath: IndexPath  = self.indexPathForRow(at: self.centerPoint) {
            return centerIndexPath
        }
        return nil
    }

    // visible or not
    func checkWhichVideoToEnableAtIndexPath() -> IndexPath? {
        guard let middleIndexPath = self.centerCellIndexPath else {return nil}
        guard let visibleIndexPaths = self.indexPathsForVisibleRows else {return nil}

        if visibleIndexPaths.contains(middleIndexPath) {
            return middleIndexPath
         }

        return nil

    }
}

Then Use at func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

 if let visibleIndex = tableView.checkWhichVideoToEnableAtIndexPath() , 
    let cellMiddle = tableView.cellForRow(at: visibleIndex) as? ListViewCell 
    {
       cellMiddle.player?.play()
   } 
    else
   {
       cell.player?.pause()
   }

Stop AVPlayer from playing in tableviewcell, It is playing in TableViewCell , but the problem is that I'm not able to stop it. You can get the cell instance and search the player instance and stop it. for view in cell.subviews So you can set seek time to 0 and pause the player. the middle of the screen is over the visible UICollectionViewCell, the focus method is called. CustomCell changeButtonImage(cell.button, play: true) } } } The buttonTapped method which starts playing a song have some logic inside. First the method signature needs @objc in order to be used in the addTarget method. The logic is a follows: Localize the button's IndexPath in the table view using the helper method.

I have implemented similar functionality like facebook video player.

-- > Auto play video --> if video pause by user don't auto play it --> Pause video as soon as it is removed from the screen

This is tested and working in every scenarios

You need to track video status in your datasource array. And I suggest you to create datasource array with class not with struct as it we need reference

var videos:[VideoAlbum] = []

var lastContentOffset:CGFloat = 0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    //       print("scrollViewDidScroll")



    let visibleCell = self.collView.indexPathsForVisibleItems
    if visibleCell.count > 0 {
        for indexPath in visibleCell {
            if videos[indexPath.row].isPlaying  || videos[indexPath.row].pausedByUser {
                continue
            }

            if let cell = self.collView.cellForItem(at: indexPath) as? CustomCell,//cell.video?.mediaType == MediaType.video,
                let rect = self.collView.layoutAttributesForItem(at: indexPath)?.center {

                //If cell's center is top of bottom of view OR cell's center is on Bottom of top of cell then play
                let cellCenterToView = self.collView.convert(rect, to: self.view)
                let cellFrameToView = self.collView.convert((self.collView.layoutAttributesForItem(at: indexPath)?.frame)!, to: self.view)

                // scrolling up
                if scrollView.contentOffset.y > lastContentOffset {
                    if cellCenterToView.y < self.view.frame.height && (cellFrameToView.height - abs(cellFrameToView.origin.y))  > self.view.frame.size.height / 2  {

                        self.pauseVideo(notFor: indexPath)

                        self.playVideoForCell(cell: cell,at: indexPath)
                    } else {
                        self.pauseVideoFor(indexPath: indexPath)
                        print("ELSE on SCROLL UP")

                    }
                } else {
                    if cellCenterToView.y > 0 && (cellFrameToView.height - abs(cellFrameToView.origin.y))  > self.view.frame.size.height / 2  {
                        print(self.view.frame.intersection(cellFrameToView).size.height)

                        self.pauseVideo(notFor: indexPath)

                        self.playVideoForCell(cell: cell,at: indexPath)

                    } else {
                        self.pauseVideoFor(indexPath: indexPath)

                        print("ELSE on SCROLL DOwn \((self.view.frame.intersection(cellFrameToView).size.height + 64))")

                    }
                }
            }
        }
    }
    lastContentOffset = scrollView.contentOffset.y
}

And Here is function for playing and pausing video

 //--------------------------------------------------------------------------------

private func pauseVideo(notFor autoPlayIndexPath:IndexPath) {
    let visibleCell = self.collView.indexPathsForVisibleItems
    if visibleCell.count > 0 {
        for indexPath in visibleCell {
            if videos[indexPath.row].isPlaying && indexPath.row != autoPlayIndexPath.row {
                guard  let cellToHide = self.collView.cellForItem(at: indexPath) as? CustomCell/*,cellToHide.video?.mediaType == MediaType.video */ else {continue}
                cellToHide.player?.pause()
                cellToHide.player?.removeTimeObserver(cellToHide.video.timeObserver)
                cellToHide.video.currentTime = cellToHide.player?.currentTime() ?? kCMTimeZero
                cellToHide.video.isPlaying = false
                NotificationCenter.default.removeObserver(cellToHide.player?.currentItem, name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
                // if cellToHide.video.timeObserver != nil  {
                //   cellToHide.player?.removeTimeObserver(cellToHide.video.timeObserver)
                // }
            }
        }
    }
}

//--------------------------------------------------------------------------------

private func pauseVideoFor(indexPath:IndexPath) {
    if videos[indexPath.row].isPlaying {
        guard  let cellToHide = self.collView.cellForItem(at: indexPath) as? CustomCell/*,cellToHide.video?.mediaType == MediaType.video */ else {return}
        cellToHide.player?.pause()
        cellToHide.player?.removeTimeObserver(cellToHide.video.timeObserver)
        cellToHide.video.currentTime = cellToHide.player?.currentTime() ?? kCMTimeZero
        cellToHide.video.isPlaying = false
        NotificationCenter.default.removeObserver(cellToHide.player?.currentItem, name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        // if cellToHide.video.timeObserver != nil  {
        //   cellToHide.player?.removeTimeObserver(cellToHide.video.timeObserver)
        // }
    }
}

And here is model that is loaded in collection view

class VideoAlbum:Codable {

    let id, image,video: String?
    let  mediaType: JSONNull?
    let type, deleted, createdOn: String?
    let modifiedOn: JSONNull?

    var isPlaying:Bool = false
    var currentTime:CMTime = kCMTimeZero
    var timeObserver:Any?  = nil
    var pausedByUser:Bool = false
    var hidePlayingControls = false


    enum CodingKeys: String, CodingKey {
        case id, image, video
        case mediaType = "media_type"
        case type, deleted
        case createdOn = "created_on"
        case modifiedOn = "modified_on"

    }
}

Hope it is helpful to you

iOS Tutorial: Want your Swift app to scroll in two directions, like , The key really is to nest a Collection View inside the Table View row. Switch to the Collection View Cell and set its background color to red. 7. Although Collection Views are a fundamental piece of UI, they can actually get I'll try playing around with the ObjC conversion to Swift and see how that goes. Below is the test case i have proceed. 1.Focus means (Ex: webedit object) 2.First find the particular cell consists of (Ex: A webedit name of "p_dev_release_found") 3. Then identify the number of edit fields available in that particular webtable (Here i have consider the object as webedit that is the reason i have calculated the webedit counut)

Radio button in uitableview ios, UITableView in JavaScript, list view with re-usable cells using flexbox If you're writing and publishing workflow with a store focused on selling in-progress ebooks. While there's a good list of Native Fonts in iOS, that you can check with this and add it as subview Handle Play Button action to Pause and Play music Set  Cells and Table View Performance. The proper use of table view cells, whether off-the-shelf or custom cell objects, is a major factor in the performance of table views. Ensure that your application does the following three things: Reuse cells. Object allocation has a performance cost, especially if the allocation has to happen repeatedly over a

Avplayer state, Pauses, resumes, or stops playing a media file that is playing or is paused. When we rebuilt our iOS app, the player was the core focus. Promo offer: Get the player in 1. you step-by-step how a table view controller works, and how you can use it. the perfect musical sibling of Drum Loops HD (1 and 2). set(url: cell. The former will notify the delegate item when it is no longer a part of the table and has been moved to the reuse pool. This can be a good time to pause ongoing animations or timers for example. The latter signal will be emitted when the delegate item has been moved back into the view. At this point you can restore the color.

URLSession Tutorial: Getting Started, This lets you focus on implementing the networking aspects of the app. Build and run the project. You'll see a view with a search bar at the top and an empty table view URLSessionDataTask: Use this task for GET requests to retrieve data You're going to need to set SearchViewController as the session  Table view cells, which are the repeatable rows, or views, shown in the table view. A table view cell is an instance of a UITableViewCell class, and that class is often subclassed to create custom table view cells. A table view controller also relies on the use of these components, behind-the scenes:

Comments
  • where can I get currentPlayIndexPath?
  • i don't use snapkit
  • ok.Here i used snapkit and set its currentindexpath from cellforRowAt in tableview method. and it works fine.@ИсмаилХасбулатов