Skip to content

Instantly share code, notes, and snippets.

@iAmrSalman
Created August 28, 2018 09:56
Show Gist options
  • Save iAmrSalman/9ad1bad84713771613593b33bcb29a33 to your computer and use it in GitHub Desktop.
Save iAmrSalman/9ad1bad84713771613593b33bcb29a33 to your computer and use it in GitHub Desktop.
[Film] Get all needed data to present a local saved video file (duration, thumbnail) #swift4 #avfoundation
import UIKit
import AVFoundation
class Film {
//MARK: - Properties
var name: String
var path: URL
var duration: String {
guard let path = path else { return "" }
return getVideoDuration(from: path)
}
var thumbnail: UIImage {
guard let path = path else { return #imageLiteral(resourceName: "placeholder-image4") }
return getVideoThumbnail(from: path) ?? #imageLiteral(resourceName: "placeholder-image4")
}
//MARK: - Initualizers
init(name: String, path: URL) {
self.name = name
self.path = path
}
//MARK: - Helpers
private func getVideoThumbnail(from path: URL?) -> UIImage? {
guard let path = path else { return nil }
do {
let asset = AVURLAsset(url: path , options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
return thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
return nil
}
}
private func getVideoDuration(from path: URL) -> String {
let asset = AVURLAsset(url: path)
let duration: CMTime = asset.duration
let totalSeconds = CMTimeGetSeconds(duration)
let hours = Int(totalSeconds / 3600)
let minutes = Int((totalSeconds.truncatingRemainder(dividingBy: 3600)) / 60)
let seconds = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment