PHAssetからファイル名や拡張子を取得する
PHAssetからファイル名を取得しようとしたらちょっと苦労したのでメモ
PHAssetのメンバにはそれっぽいものがなかった。
結論を言うと
- Private Apiで取得
- PHImageManager経由で取得
上記のどちらかのようだ。
Private Apiで取得
// 'asset'は PHAssetのインスタンス let filename = asset.value(forKey: "filename")
PHImageManager経由で取得
PHImageManagerの関数の戻り値から取得できる
画像とビデオでそれぞれ取得方法が違った
// 'asset'は PHAssetのインスタンス switch asset.mediaType { case .image: let option = PHImageRequestOptions() option.deliveryMode = .highQualityFormat PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: option) { (image, info) in if let url = info?["PHImageFileURLKey"] as? URL { print(url.lastPathComponent) print(url.pathExtension) } } case .video: let option = PHVideoRequestOptions() option.deliveryMode = .highQualityFormat PHImageManager.default().requestAVAsset(forVideo: asset, options: option, resultHandler: { (avAsset, audioMix, info) in if let tokenStr = info?["PHImageFileSandboxExtensionTokenKey"] as? String { let tokenKeys = tokenStr.components(separatedBy: ";") let urlStr = tokenKeys.filter { $0.contains("/private/var/mobile/Media") }.first if let urlStr = urlStr { if let url = URL(string: urlStr) { print(url.lastPathComponent) print(url.pathExtension) } } } }) default: break }