2// Print the size of every item in my Photos Library.
3// See https://alexwlchan.net/2023/finding-big-photos/
7struct AssetData: Codable {
8 var localIdentifier: String
9 var originalFilename: String
13/// Returns a list of assets in the Photos Library.
15/// The list is sorted by file size, from largest to smallest.
16func getAssetsBySize() -> [AssetData] {
17 var allAssets: [AssetData] = []
19 let options: PHFetchOptions? = nil
21 PHAsset.fetchAssets(with: options)
22 .enumerateObjects({ (asset, _, _) in
23 let resource = PHAssetResource.assetResources(for: asset)[0]
26 localIdentifier: asset.localIdentifier,
27 originalFilename: resource.originalFilename,
28 fileSize: resource.value(forKey: "fileSize") as! Int64
31 allAssets.append(data)
34 allAssets.sort { $0.fileSize > $1.fileSize }
39/// Quick extension to allow left-padding a string in Swift
41/// By user2878850 on Stack Overflow:
42/// https://stackoverflow.com/a/69859859/1558022
44 func leftPadding(toLength: Int, withPad: String) -> String {
47 .padding(toLength: toLength, withPad: withPad, startingAt: 0)
53let bcf = ByteCountFormatter()
55for photo in getAssetsBySize() {
58 .string(fromByteCount: photo.fileSize)
59 .leftPadding(toLength: 8, withPad: " ")
60 print("\(size) \(photo.originalFilename)")