Error occurs on tvos 10.0

91 views Asked by At

I am working on tvos application , it is working fine on 10.1 (newer version) but it gives the error when i am running on previous version (10.0) after refresh(1 min).

error message is

enter image description here

my code is

NewsViewController

import UIKit
import Kingfisher
private let reuseIdentifier = "trenddingCell"
private let reuseIdentifierRegular = "regularCell"
class NewsViewController: UICollectionViewController {
    @IBOutlet var mainCollectionView: UICollectionView!

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var backgroundMessageLabel:UILabel?
    var focusFlag:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(NewsViewController.presentController(_:)), name: NSNotification.Name(rawValue: "videoInfo"), object: nil)

        let menuPressRecognizer = UITapGestureRecognizer()
        menuPressRecognizer.addTarget(self, action: #selector(NewsViewController.menuButtonAction(_:)))
        menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.menu.rawValue as Int)]
        self.view.addGestureRecognizer(menuPressRecognizer)

        self.tabBarController?.tabBar.preferredFocusedView
        self.setNeedsFocusUpdate()
        self.updateFocusIfNeeded()

    }

    func menuButtonAction(_ ges:UITapGestureRecognizer){

        self.tabBarController?.tabBar.canBecomeFocused
        self.tabBarController?.preferredFocusedView
        self.tabBarController?.setNeedsFocusUpdate()
        self.tabBarController?.updateFocusIfNeeded()
    }

    override func viewWillAppear(_ animated: Bool) {

            if appDelegate.dataFeedDetail.feedType == "J" || appDelegate.dataFeedDetail.feedType == "L"{
                self.title = "ON DEMAND"
            }
            else{
                self.title = "ON DEMAND"
            }

        //WebTrends().eventForTabBarItemFocus("News", menu: "news")
        WebTrends().eventForTabBarItemFocus("News", channelName: "", menu: "news")
        appDelegate.viewController = self
        appDelegate.playerViewController = self
        if appDelegate.categoryNewsArray.count == 0{
            addBackgroundMessageLabel()
        }else{

            removeBackgroundMessage()
            mainCollectionView.isHidden = false
            if !focusFlag{
                mainCollectionView.reloadData()
            }
        }
        focusFlag = false
    }
    func loadNewData() {

        DispatchQueue.main.async(execute: { () -> Void in
            if self.appDelegate.categoryNewsArray.count > 0 {
                self.removeBackgroundMessage()
                self.mainCollectionView.isHidden = false
                self.mainCollectionView.reloadData()
            }
        })
    }

    // MARK: - Collection Data Source.
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("begin numberOfItemsInSection")

        return appDelegate.categoryNewsArray.count

    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                print("begin cellForItemAt")

        if indexPath.item == 0{

            let cellTrendding = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TrendingCollectionCell
            let trindingValue = appDelegate.categoryNewsArray.object(at: indexPath.item) as! NSMutableDictionary
            cellTrendding.trenddingLabelView.text = trindingValue.object(forKey: "title") as? String
                    print("end cellTrendding")

            return cellTrendding
        }else{

            let cellRegular = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierRegular, for: indexPath) as! RegularCollectionCell
            let trindingValue = appDelegate.categoryNewsArray.object(at: indexPath.item) as! NSMutableDictionary
            cellRegular.categoryLabelView.text = trindingValue.object(forKey: "title") as? String
                    print("end cellRegular")

            return cellRegular
        }
    }

    // MARK: - CollectionViewDelegate.
    override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        print("begin willDisplay")

        if indexPath.item == 0{
            guard let cell = cell as? TrendingCollectionCell else { fatalError("Expected to display a `TrendingCollectionCell`.") }
            let trending = appDelegate.categoryNewsArray.object(at: indexPath.item)
            cell.configureWithDataItems(trending as! NSMutableDictionary, jIndex: indexPath.item)
        }else{
            guard let cell = cell as? RegularCollectionCell else { fatalError("Expected to display a `RegularCollectionCell`.") }
            let trending = appDelegate.categoryNewsArray.object(at: indexPath.item) as! NSMutableDictionary
            print("appDelegate.categoryNewsArray====================\(trending.count)")
            cell.configureWithDataItems(trending, jIndex: indexPath.item)
        }
        print("end willDisplay")

    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        print("begin layout")
        if indexPath.item == 0 {
            return CGSize(width: view.frame.width, height: 410)
        }else{
            return CGSize(width: view.frame.width, height: 320)
        }
    }

     override func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool{
        print("begin canFocusItemAt\(indexPath.item)")
        return false
    }

    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {

    }

    // MARK: - Present Controller.
     func presentController(_ notification:Notification) {
            print("begin presentController")

        let notificationData:NSDictionary = NSDictionary(dictionary: notification.userInfo!)
        focusFlag = true
        let playerVC = self.storyboard?.instantiateViewController(withIdentifier: "VideoPlayerViewController") as! VideoPlayerViewController

        playerVC.videoIdentifier = "NewsView"
        playerVC.videoCategoryNameandTitle = notificationData.object(forKey: "channelname") as! String as NSString
        playerVC.navigationName = "News/\(notificationData.object(forKey: "channelname") as! String)" as NSString
        playerVC.indexPath = notificationData.object(forKey: "indexpath") as! Int
        playerVC.seriesShowDfpUrl = notificationData.object(forKey: "dfptag") as! String as NSString!
        playerVC.seriesShows_Array = notificationData.object(forKey: "metaData") as! NSArray
        playerVC.videoMaxShow = notificationData.object(forKey: "max_show") as! String
        playerVC.adInterval = notificationData.object(forKey: "adinterval") as! Int

        playerVC.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        playerVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
        self.view.window?.rootViewController?.present(playerVC, animated: true, completion: nil)
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        KingfisherManager.shared.cache.clearMemoryCache()
        KingfisherManager.shared.cache.clearDiskCache()
    }

    func addBackgroundMessageLabel(){
        if backgroundMessageLabel == nil {
            backgroundMessageLabel = UILabel(frame: CGRect.zero)
            backgroundMessageLabel!.center = view.center
            backgroundMessageLabel! = backgroundMessageLabel!.setLabelView(backgroundMessageLabel!, message: kNoDataMessage )
            self.view.addSubview(backgroundMessageLabel!)
            NSLayoutConstraint(item: backgroundMessageLabel!, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
            NSLayoutConstraint(item: backgroundMessageLabel!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
        }

    }
    func removeBackgroundMessage(){
        if self.backgroundMessageLabel != nil {
            self.backgroundMessageLabel!.removeFromSuperview()
            self.backgroundMessageLabel = nil
        }

    }
}

extension UILabel {
    func setLabelView(_ label:UILabel, message:String) -> UILabel {
        let backgroundMessageLabel = label
        backgroundMessageLabel.text = message
        backgroundMessageLabel.textAlignment = .center
        backgroundMessageLabel.font =  UIFont(name: "SFUIDisplay-Regular", size: 32.0)
        backgroundMessageLabel.textColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)//UIColor.whiteColor()
        backgroundMessageLabel.backgroundColor = .clear
        backgroundMessageLabel.translatesAutoresizingMaskIntoConstraints = false
        return backgroundMessageLabel

    }
}

RegularCollectionCell

import UIKit
import Kingfisher

private let cellId = "appCellId"
class RegularCollectionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet var categoryCollectionView: UICollectionView!
    @IBOutlet var categoryLabelView: UILabel!
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var dataItems = NSMutableDictionary()
    var jsonIndex:Int!

    // MARK: Configuration.
    func configureWithDataItems(_ dataItems: NSMutableDictionary, jIndex:Int) {
        self.dataItems = dataItems
        categoryCollectionView.reloadData()
//        categoryCollectionView.remembersLastFocusedIndexPath = true
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let seriesShows_Array = self.dataItems.value(forKey: "max_shows") as? String
        let topVideos = self.dataItems.value(forKey: "datafeed") as? NSArray
        if seriesShows_Array != "" {
            if topVideos!.count > Int(seriesShows_Array!)! {
                return Int(seriesShows_Array!)! as Int
            }
        }
        if topVideos != nil && topVideos!.count > 0{
            print("Crash numberOfItemsInSection",topVideos!.count)
            return topVideos!.count
        }else{
            return 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            print("begin cellForItemAt")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomCollectionCell
                let topVideos = (self.dataItems.value(forKey: "datafeed") as! NSArray).object(at: indexPath.item) as! JsonModel

        cell.custom_LabelView.text = topVideos.videoTitle as String
        let thumnailURL = topVideos.videoThumbnail as String
                print("thumnailURL",thumnailURL)
        let validUrl = thumnailURL.checkValidUrl(thumnailURL as String)
                print("validUrl",validUrl)

        let url = URL(string: validUrl)
                print("url",url!)

        cell.custom_ImageView.kf.setImage(with:  url!, placeholder: UIImage(named: "not_found"), options: [.transition(ImageTransition.fade(0.5))], progressBlock: nil, completionHandler: nil)
        cell.custom_LabelView.fadeLength = 100.0
        cell.custom_LabelView.shutdownLabel()
        print("end cellForItemAt")
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let dfpTag:String = self.dataItems.object(forKey: "dfp_tag") as! String
        let adIntervalStr = self.dataItems.object(forKey: "ad_interval") as! String
        let adInterval:Int!
        if adIntervalStr == ""{
            adInterval = 0
        }else{
            adInterval = Int(adIntervalStr)
        }
        let channelNameStr:NSString = self.dataItems.object(forKey: "title") as! String as NSString
        let topVideos = self.dataItems.value(forKey: "datafeed") as! NSArray
        let maxShow = self.dataItems.value(forKey: "max_shows") as! String
        var tempDict: NSDictionary = [NSString:AnyObject]() as NSDictionary
        tempDict = ["channelname": channelNameStr, "indexpath": indexPath.item, "dfptag": dfpTag, "adinterval": adInterval, "metaData": topVideos, "max_show": maxShow]
        NotificationCenter.default.post(name: Notification.Name(rawValue: "videoInfo"), object: nil, userInfo:tempDict as? [AnyHashable: Any])
    }
}
1

There are 1 answers

0
Gaurav On BEST ANSWER

Finally I have resolved the problem.

Replace

self.mainCollectionView.reloadItems(at: self.mainCollectionView.indexPathsForVisibleItems)

from

self.mainCollectionView.reloadata