|
| 1 | +// |
| 2 | +// AVPlayerViewControllerExtension.swift |
| 3 | +// AVPlayerViewController-Subtitles |
| 4 | +// |
| 5 | +// Created by Crt Gregoric on 11/02/2022. |
| 6 | +// Copyright © 2022 Marc Hervera. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import AVKit |
| 10 | + |
| 11 | +public extension AVPlayerViewController { |
| 12 | + |
| 13 | + private struct AssociatedKeys { |
| 14 | + static var FontKey = "FontKey" |
| 15 | + static var ColorKey = "FontKey" |
| 16 | + static var SubtitleKey = "SubtitleKey" |
| 17 | + static var SubtitleHeightKey = "SubtitleHeightKey" |
| 18 | + static var PayloadKey = "PayloadKey" |
| 19 | + } |
| 20 | + |
| 21 | + // MARK: - Public properties |
| 22 | + |
| 23 | + var subtitleLabel: UILabel? { |
| 24 | + get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleKey) as? UILabel } |
| 25 | + set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } |
| 26 | + } |
| 27 | + |
| 28 | + // MARK: - Private properties |
| 29 | + |
| 30 | + fileprivate var subtitleLabelHeightConstraint: NSLayoutConstraint? { |
| 31 | + get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey) as? NSLayoutConstraint } |
| 32 | + set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } |
| 33 | + } |
| 34 | + |
| 35 | + fileprivate var parsedPayload: NSDictionary? { |
| 36 | + get { return objc_getAssociatedObject(self, &AssociatedKeys.PayloadKey) as? NSDictionary } |
| 37 | + set (value) { objc_setAssociatedObject(self, &AssociatedKeys.PayloadKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } |
| 38 | + } |
| 39 | + |
| 40 | + // MARK: - Public methods |
| 41 | + |
| 42 | + func addSubtitles() { |
| 43 | + // Create label |
| 44 | + addSubtitleLabel() |
| 45 | + } |
| 46 | + |
| 47 | + func open(fileFromLocal filePath: URL, encoding: String.Encoding = .utf8) throws { |
| 48 | + let contents = try String(contentsOf: filePath, encoding: encoding) |
| 49 | + show(subtitles: contents) |
| 50 | + } |
| 51 | + |
| 52 | + func open(fileFromRemote filePath: URL, encoding: String.Encoding = .utf8) { |
| 53 | + subtitleLabel?.text = "..." |
| 54 | + let dataTask = URLSession.shared.dataTask(with: filePath) { data, response, error in |
| 55 | + if let httpResponse = response as? HTTPURLResponse { |
| 56 | + let statusCode = httpResponse.statusCode |
| 57 | + |
| 58 | + //Check status code |
| 59 | + if statusCode != 200 { |
| 60 | + NSLog("Subtitle Error: \(httpResponse.statusCode) - \(error?.localizedDescription ?? "")") |
| 61 | + return |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // Update UI elements on main thread |
| 66 | + DispatchQueue.main.async { |
| 67 | + self.subtitleLabel?.text = "" |
| 68 | + if let checkData = data as Data?, let contents = String(data: checkData, encoding: encoding) { |
| 69 | + self.show(subtitles: contents) |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + dataTask.resume() |
| 74 | + } |
| 75 | + |
| 76 | + func show(subtitles string: String) { |
| 77 | + // Parse |
| 78 | + parsedPayload = try? Subtitles.parseSubRip(string) |
| 79 | + if let parsedPayload = parsedPayload { |
| 80 | + addPeriodicNotification(parsedPayload: parsedPayload) |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + func showByDictionary(dictionaryContent: NSMutableDictionary) { |
| 85 | + // Add Dictionary content direct to Payload |
| 86 | + parsedPayload = dictionaryContent |
| 87 | + if let parsedPayload = parsedPayload { |
| 88 | + addPeriodicNotification(parsedPayload: parsedPayload) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + func addPeriodicNotification(parsedPayload: NSDictionary) { |
| 93 | + // Add periodic notifications |
| 94 | + let interval = CMTimeMake(value: 1, timescale: 60) |
| 95 | + self.player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in |
| 96 | + guard let strongSelf = self, let label = strongSelf.subtitleLabel else { |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + // Search && show subtitles |
| 101 | + label.text = Subtitles.searchSubtitles(strongSelf.parsedPayload, time.seconds) |
| 102 | + |
| 103 | + // Adjust size |
| 104 | + let baseSize = CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude) |
| 105 | + let rect = label.sizeThatFits(baseSize) |
| 106 | + if label.text != nil { |
| 107 | + strongSelf.subtitleLabelHeightConstraint?.constant = rect.height + 5.0 |
| 108 | + } else { |
| 109 | + strongSelf.subtitleLabelHeightConstraint?.constant = rect.height |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + fileprivate func addSubtitleLabel() { |
| 115 | + guard subtitleLabel == nil else { |
| 116 | + return |
| 117 | + } |
| 118 | + |
| 119 | + // Label |
| 120 | + subtitleLabel = UILabel() |
| 121 | + subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false |
| 122 | + subtitleLabel?.backgroundColor = UIColor.clear |
| 123 | + subtitleLabel?.textAlignment = .center |
| 124 | + subtitleLabel?.numberOfLines = 0 |
| 125 | + let fontSize = UIDevice.current.userInterfaceIdiom == .pad ? 40.0 : 22.0 |
| 126 | + subtitleLabel?.font = UIFont.boldSystemFont(ofSize: fontSize) |
| 127 | + subtitleLabel?.textColor = .white |
| 128 | + subtitleLabel?.layer.shadowColor = UIColor.black.cgColor |
| 129 | + subtitleLabel?.layer.shadowOffset = CGSize(width: 1.0, height: 1.0) |
| 130 | + subtitleLabel?.layer.shadowOpacity = 0.9 |
| 131 | + subtitleLabel?.layer.shadowRadius = 1.0 |
| 132 | + subtitleLabel?.layer.shouldRasterize = true |
| 133 | + subtitleLabel?.layer.rasterizationScale = UIScreen.main.scale |
| 134 | + subtitleLabel?.lineBreakMode = .byWordWrapping |
| 135 | + |
| 136 | + contentOverlayView?.addSubview(subtitleLabel!) |
| 137 | + |
| 138 | + // Position |
| 139 | + var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[l]-(20)-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!]) |
| 140 | + contentOverlayView?.addConstraints(constraints) |
| 141 | + constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[l]-(30)-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!]) |
| 142 | + contentOverlayView?.addConstraints(constraints) |
| 143 | + subtitleLabelHeightConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1.0, constant: 30.0) |
| 144 | + contentOverlayView?.addConstraint(subtitleLabelHeightConstraint!) |
| 145 | + } |
| 146 | + |
| 147 | +} |
0 commit comments