Last active
November 14, 2023 13:24
-
-
Save gboyegadada/e7b7343663b0e718b1ec8493d085216b to your computer and use it in GitHub Desktop.
[ Swift for Mac OS ] Load video meta data from URL – duration, natural size and creation date (and more) in Swift. This looks expensive so make sure you store results somewhere for re-use. Bonus: get image pixel dimensions from (local image file) URL!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For images... | |
import AppKit | |
extension URL { | |
func getImageSize() -> CGSize? { | |
guard let src = CGImageSourceCreateWithURL(self as CFURL, nil) else { | |
return nil | |
} | |
guard let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil), | |
let properties = props as? [String: AnyObject] else { | |
return nil | |
} | |
guard let w = properties["PixelWidth"], let h = properties["PixelHeight"] else { | |
return nil | |
} | |
let size = CGSize( | |
width: w.intValue as Int, | |
height: h.intValue as Int) | |
return size | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For video... | |
import AVKit | |
struct VideoInfo { | |
let isPlayable: Bool | |
let duration: Double | |
let creationDate: Date? | |
let size: CGSize? | |
} | |
extension URL { | |
func getVideoInfo() async -> VideoInfo? { | |
let asset = AVURLAsset(url: self) | |
do { | |
let (isPlayable, duration, tracks, creationDate) = try await asset.load(.isPlayable, .duration, .tracks, .creationDate) | |
let (naturalSize) = try await tracks.first?.load(.naturalSize) | |
let (date) = try await creationDate?.load(.dateValue) | |
return VideoInfo( | |
isPlayable: isPlayable, | |
duration: duration.seconds, | |
creationDate: date, | |
size: naturalSize | |
) | |
} catch { | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment