reformat iOS code

This commit is contained in:
Wenqi Li 2023-07-27 20:28:38 +08:00
parent d21edf5cac
commit 7c48244058

View File

@ -10,7 +10,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
let instance = SwiftPhotoGalleryPlugin() let instance = SwiftPhotoGalleryPlugin()
registrar.addMethodCallDelegate(instance, channel: channel) registrar.addMethodCallDelegate(instance, channel: channel)
} }
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if(call.method == "listAlbums") { if(call.method == "listAlbums") {
let arguments = call.arguments as! Dictionary<String, AnyObject> let arguments = call.arguments as! Dictionary<String, AnyObject>
@ -26,7 +26,14 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
let skip = arguments["skip"] as? NSNumber let skip = arguments["skip"] as? NSNumber
let take = arguments["take"] as? NSNumber let take = arguments["take"] as? NSNumber
let lightWeight = arguments["lightWeight"] as? Bool let lightWeight = arguments["lightWeight"] as? Bool
result(listMedia(albumId: albumId, mediumType: mediumType, newest: newest, skip: skip, take: take, lightWeight: lightWeight)) result(listMedia(
albumId: albumId,
mediumType: mediumType,
newest: newest,
skip: skip,
take: take,
lightWeight: lightWeight
))
} }
else if(call.method == "getMedium") { else if(call.method == "getMedium") {
let arguments = call.arguments as! Dictionary<String, AnyObject> let arguments = call.arguments as! Dictionary<String, AnyObject>
@ -104,9 +111,9 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
result(FlutterMethodNotImplemented) result(FlutterMethodNotImplemented)
} }
} }
private var assetCollections : [PHAssetCollection] = [] private var assetCollections: [PHAssetCollection] = []
private func listAlbums(mediumType: String?, hideIfEmpty: Bool? = true) -> [[String: Any?]] { private func listAlbums(mediumType: String?, hideIfEmpty: Bool? = true) -> [[String: Any?]] {
self.assetCollections = [] self.assetCollections = []
let fetchOptions = PHFetchOptions() let fetchOptions = PHFetchOptions()
@ -115,16 +122,16 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
} }
var albums = [[String: Any?]]() var albums = [[String: Any?]]()
var albumIds = Set<String>() var albumIds = Set<String>()
func addCollection (collection: PHAssetCollection, hideIfEmpty: Bool) -> Void { func addCollection (collection: PHAssetCollection, hideIfEmpty: Bool) -> Void {
let kRecentlyDeletedCollectionSubtype = PHAssetCollectionSubtype(rawValue: 1000000201) let kRecentlyDeletedCollectionSubtype = PHAssetCollectionSubtype(rawValue: 1000000201)
guard collection.assetCollectionSubtype != kRecentlyDeletedCollectionSubtype else { return } guard collection.assetCollectionSubtype != kRecentlyDeletedCollectionSubtype else { return }
// De-duplicate by id. // De-duplicate by id.
let albumId = collection.localIdentifier let albumId = collection.localIdentifier
guard !albumIds.contains(albumId) else { return } guard !albumIds.contains(albumId) else { return }
albumIds.insert(albumId) albumIds.insert(albumId)
let count = countMedia(collection: collection, mediumType: mediumType) let count = countMedia(collection: collection, mediumType: mediumType)
if(count > 0 || !hideIfEmpty) { if(count > 0 || !hideIfEmpty) {
self.assetCollections.append(collection) self.assetCollections.append(collection)
@ -135,69 +142,89 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
]) ])
} }
} }
func processPHAssetCollections(fetchResult: PHFetchResult<PHAssetCollection>, hideIfEmpty: Bool) -> Void { func processPHAssetCollections(fetchResult: PHFetchResult<PHAssetCollection>, hideIfEmpty: Bool) -> Void {
fetchResult.enumerateObjects { (assetCollection, _, _) in fetchResult.enumerateObjects { (assetCollection, _, _) in
addCollection(collection: assetCollection, hideIfEmpty: hideIfEmpty) addCollection(collection: assetCollection, hideIfEmpty: hideIfEmpty)
} }
} }
func processPHCollections (fetchResult: PHFetchResult<PHCollection>, hideIfEmpty: Bool) -> Void { func processPHCollections (fetchResult: PHFetchResult<PHCollection>, hideIfEmpty: Bool) -> Void {
fetchResult.enumerateObjects { (collection, _, _) in fetchResult.enumerateObjects { (collection, _, _) in
if let assetCollection = collection as? PHAssetCollection { if let assetCollection = collection as? PHAssetCollection {
addCollection(collection: assetCollection, hideIfEmpty: hideIfEmpty) addCollection(collection: assetCollection, hideIfEmpty: hideIfEmpty)
} else if let collectionList = collection as? PHCollectionList { } else if let collectionList = collection as? PHCollectionList {
processPHCollections(fetchResult: PHCollectionList.fetchCollections(in: collectionList, options: nil), hideIfEmpty: hideIfEmpty) processPHCollections(
fetchResult: PHCollectionList.fetchCollections(in: collectionList, options: nil),
hideIfEmpty: hideIfEmpty
)
} }
} }
} }
// Smart Albums. // Smart Albums.
processPHAssetCollections( processPHAssetCollections(
fetchResult: PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: fetchOptions), fetchResult: PHAssetCollection.fetchAssetCollections(
with: .smartAlbum,
subtype: .albumRegular,
options: fetchOptions
),
hideIfEmpty: hideIfEmpty ?? true hideIfEmpty: hideIfEmpty ?? true
) )
// User-created collections. // User-created collections.
processPHCollections( processPHCollections(
fetchResult: PHAssetCollection.fetchTopLevelUserCollections(with: fetchOptions), fetchResult: PHAssetCollection.fetchTopLevelUserCollections(with: fetchOptions),
hideIfEmpty: hideIfEmpty ?? true hideIfEmpty: hideIfEmpty ?? true
) )
albums.insert([ albums.insert([
"id": "__ALL__", "id": "__ALL__",
"name": "All", "name": "All",
"count" : countMedia(collection: nil, mediumType: mediumType), "count": countMedia(collection: nil, mediumType: mediumType),
], at: 0) ], at: 0)
return albums return albums
} }
private func countMedia(collection: PHAssetCollection?, mediumType: String?) -> Int { private func countMedia(collection: PHAssetCollection?, mediumType: String?) -> Int {
let options = PHFetchOptions() let options = PHFetchOptions()
options.predicate = self.predicateFromMediumType(mediumType: mediumType) options.predicate = self.predicateFromMediumType(mediumType: mediumType)
if(collection == nil) { if(collection == nil) {
return PHAsset.fetchAssets(with: options).count return PHAsset.fetchAssets(with: options).count
} }
return PHAsset.fetchAssets(in: collection ?? PHAssetCollection.init(), options: options).count return PHAsset.fetchAssets(in: collection ?? PHAssetCollection.init(), options: options).count
} }
private func listMedia(albumId: String, mediumType: String?, newest: Bool, skip: NSNumber?, take: NSNumber?, lightWeight: Bool? = false) -> NSDictionary { private func listMedia(
albumId: String,
mediumType: String?,
newest: Bool,
skip: NSNumber?,
take: NSNumber?,
lightWeight: Bool? = false
) -> NSDictionary {
let fetchOptions = PHFetchOptions() let fetchOptions = PHFetchOptions()
fetchOptions.predicate = predicateFromMediumType(mediumType: mediumType) fetchOptions.predicate = predicateFromMediumType(mediumType: mediumType)
fetchOptions.sortDescriptors = [ fetchOptions.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: newest ? false : true), NSSortDescriptor(key: "creationDate", ascending: newest ? false : true),
NSSortDescriptor(key: "modificationDate", ascending: newest ? false : true) NSSortDescriptor(key: "modificationDate", ascending: newest ? false : true)
] ]
let collection = self.assetCollections.first(where: { (collection) -> Bool in let collection = self.assetCollections.first(where: { (collection) -> Bool in
collection.localIdentifier == albumId collection.localIdentifier == albumId
}) })
let fetchResult = albumId == "__ALL__" let fetchResult: PHFetchResult<PHAsset>
? PHAsset.fetchAssets(with: fetchOptions) if(albumId == "__ALL__") {
: PHAsset.fetchAssets(in: collection ?? PHAssetCollection.init(), options: fetchOptions) fetchResult = PHAsset.fetchAssets(with: fetchOptions)
} else {
fetchResult = PHAsset.fetchAssets(
in: collection ?? PHAssetCollection.init(),
options: fetchOptions
)
}
let start = skip?.intValue ?? 0 let start = skip?.intValue ?? 0
let total = fetchResult.count let total = fetchResult.count
let end = take == nil ? total : min(start + take!.intValue, total) let end = take == nil ? total : min(start + take!.intValue, total)
@ -210,20 +237,20 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
items.append(getMediumFromAsset(asset: asset)) items.append(getMediumFromAsset(asset: asset))
} }
} }
return [ return [
"start": start, "start": start,
"items": items, "items": items,
] ]
} }
private func getMedium(mediumId: String) throws -> [String: Any?] { private func getMedium(mediumId: String) throws -> [String: Any?] {
let fetchOptions = PHFetchOptions() let fetchOptions = PHFetchOptions()
if #available(iOS 9, *) { if #available(iOS 9, *) {
fetchOptions.fetchLimit = 1 fetchOptions.fetchLimit = 1
} }
let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions) let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions)
if (assets.count <= 0) { if (assets.count <= 0) {
throw NSError(domain: "photo_gallery", code: 404) throw NSError(domain: "photo_gallery", code: 404)
} else { } else {
@ -231,7 +258,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
return getMediumFromAsset(asset: asset) return getMediumFromAsset(asset: asset)
} }
} }
private func getThumbnail( private func getThumbnail(
mediumId: String, mediumId: String,
width: NSNumber?, width: NSNumber?,
@ -245,25 +272,28 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
fetchOptions.fetchLimit = 1 fetchOptions.fetchLimit = 1
} }
let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions) let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions)
if (assets.count > 0) { if (assets.count > 0) {
let asset: PHAsset = assets[0] let asset: PHAsset = assets[0]
let options = PHImageRequestOptions() let options = PHImageRequestOptions()
options.isSynchronous = false options.isSynchronous = false
options.version = .current options.version = .current
options.deliveryMode = (highQuality ?? false) ? .highQualityFormat : .fastFormat options.deliveryMode = (highQuality ?? false) ? .highQualityFormat : .fastFormat
options.isNetworkAccessAllowed = true options.isNetworkAccessAllowed = true
let imageSize = CGSize(width: width?.intValue ?? 128, height: height?.intValue ?? 128) let imageSize = CGSize(width: width?.intValue ?? 128, height: height?.intValue ?? 128)
manager.requestImage( manager.requestImage(
for: asset, for: asset,
targetSize: CGSize(width: imageSize.width * UIScreen.main.scale, height: imageSize.height * UIScreen.main.scale), targetSize: CGSize(
width: imageSize.width * UIScreen.main.scale,
height: imageSize.height * UIScreen.main.scale
),
contentMode: PHImageContentMode.aspectFill, contentMode: PHImageContentMode.aspectFill,
options: options, options: options,
resultHandler: {(uiImage: UIImage?, info) in resultHandler: { (uiImage: UIImage?, info) in
guard let image = uiImage else { guard let image = uiImage else {
completion(nil , NSError(domain: "photo_gallery", code: 404, userInfo: nil)) completion(nil, NSError(domain: "photo_gallery", code: 404, userInfo: nil))
return return
} }
let bytes = image.jpegData(compressionQuality: CGFloat(70)) let bytes = image.jpegData(compressionQuality: CGFloat(70))
@ -272,10 +302,10 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
) )
return return
} }
completion(nil , NSError(domain: "photo_gallery", code: 404, userInfo: nil)) completion(nil, NSError(domain: "photo_gallery", code: 404, userInfo: nil))
} }
private func getAlbumThumbnail( private func getAlbumThumbnail(
albumId: String, albumId: String,
mediumType: String?, mediumType: String?,
@ -295,34 +325,37 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
if #available(iOS 9, *) { if #available(iOS 9, *) {
fetchOptions.fetchLimit = 1 fetchOptions.fetchLimit = 1
} }
let assets = albumId == "__ALL__" ? let assets: PHFetchResult<PHAsset>
PHAsset.fetchAssets(with: fetchOptions) : if(albumId == "__ALL__") {
PHAsset.fetchAssets(in: self.assetCollections.first(where: { (collection) -> Bool in assets = PHAsset.fetchAssets(with: fetchOptions)
} else {
assets = PHAsset.fetchAssets(in: self.assetCollections.first(where: { (collection) -> Bool in
collection.localIdentifier == albumId collection.localIdentifier == albumId
})!, options: fetchOptions) })!, options: fetchOptions)
}
if (assets.count > 0) { if (assets.count > 0) {
let asset: PHAsset = assets[0] let asset: PHAsset = assets[0]
let options = PHImageRequestOptions() let options = PHImageRequestOptions()
options.isSynchronous = false options.isSynchronous = false
options.version = .current options.version = .current
options.deliveryMode = (highQuality ?? false) ? .highQualityFormat : .fastFormat options.deliveryMode = (highQuality ?? false) ? .highQualityFormat : .fastFormat
options.isNetworkAccessAllowed = true options.isNetworkAccessAllowed = true
let imageSize = CGSize(width: width ?? 128, height: height ?? 128) let imageSize = CGSize(width: width ?? 128, height: height ?? 128)
manager.requestImage( manager.requestImage(
for: asset, for: asset,
targetSize: CGSize( targetSize: CGSize(
width: imageSize.width * UIScreen.main.scale, width: imageSize.width * UIScreen.main.scale,
height: imageSize.height * UIScreen.main.scale height: imageSize.height * UIScreen.main.scale
), ),
contentMode: PHImageContentMode.aspectFill, contentMode: PHImageContentMode.aspectFill,
options: options, options: options,
resultHandler: {(uiImage: UIImage?, info) in resultHandler: { (uiImage: UIImage?, info) in
guard let image = uiImage else { guard let image = uiImage else {
completion(nil , NSError(domain: "photo_gallery", code: 404, userInfo: nil)) completion(nil, NSError(domain: "photo_gallery", code: 404, userInfo: nil))
return return
} }
let bytes = image.jpegData(compressionQuality: CGFloat(80)) let bytes = image.jpegData(compressionQuality: CGFloat(80))
@ -331,19 +364,19 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
) )
return return
} }
completion(nil , NSError(domain: "photo_gallery", code: 404, userInfo: nil)) completion(nil, NSError(domain: "photo_gallery", code: 404, userInfo: nil))
} }
private func getFile(mediumId: String, mimeType: String?, completion: @escaping (String?, Error?) -> Void) { private func getFile(mediumId: String, mimeType: String?, completion: @escaping (String?, Error?) -> Void) {
let manager = PHImageManager.default() let manager = PHImageManager.default()
let fetchOptions = PHFetchOptions() let fetchOptions = PHFetchOptions()
if #available(iOS 9, *) { if #available(iOS 9, *) {
fetchOptions.fetchLimit = 1 fetchOptions.fetchLimit = 1
} }
let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions) let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions)
if (assets.count > 0) { if (assets.count > 0) {
let asset: PHAsset = assets[0] let asset: PHAsset = assets[0]
if(asset.mediaType == PHAssetMediaType.image) { if(asset.mediaType == PHAssetMediaType.image) {
@ -352,7 +385,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
options.version = .current options.version = .current
options.deliveryMode = .highQualityFormat options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true options.isNetworkAccessAllowed = true
manager.requestImageData( manager.requestImageData(
for: asset, for: asset,
options: options, options: options,
@ -381,13 +414,12 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
}) })
} }
) )
} else if(asset.mediaType == PHAssetMediaType.video } else if(asset.mediaType == PHAssetMediaType.video || asset.mediaType == PHAssetMediaType.audio) {
|| asset.mediaType == PHAssetMediaType.audio) {
let options = PHVideoRequestOptions() let options = PHVideoRequestOptions()
options.version = .current options.version = .current
options.deliveryMode = .highQualityFormat options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true options.isNetworkAccessAllowed = true
manager.requestAVAsset( manager.requestAVAsset(
forVideo: asset, forVideo: asset,
options: options, options: options,
@ -409,7 +441,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
} }
} }
} }
private func cacheImage(asset: PHAsset, data: Data, mimeType: String) -> String? { private func cacheImage(asset: PHAsset, data: Data, mimeType: String) -> String? {
if mimeType == "image/jpeg" { if mimeType == "image/jpeg" {
let filepath = self.exportPathForAsset(asset: asset, ext: ".jpeg") let filepath = self.exportPathForAsset(asset: asset, ext: ".jpeg")
@ -425,7 +457,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
return nil return nil
} }
} }
private func getMediumFromAsset(asset: PHAsset) -> [String: Any?] { private func getMediumFromAsset(asset: PHAsset) -> [String: Any?] {
let filename = self.extractFilenameFromAsset(asset: asset) let filename = self.extractFilenameFromAsset(asset: asset)
let mimeType = self.extractMimeTypeFromAsset(asset: asset) let mimeType = self.extractMimeTypeFromAsset(asset: asset)
@ -447,7 +479,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
"modifiedDate": (asset.modificationDate != nil) ? NSInteger(asset.modificationDate!.timeIntervalSince1970 * 1000) : nil "modifiedDate": (asset.modificationDate != nil) ? NSInteger(asset.modificationDate!.timeIntervalSince1970 * 1000) : nil
] ]
} }
private func getMediumFromAssetLightWeight(asset: PHAsset) -> [String: Any?] { private func getMediumFromAssetLightWeight(asset: PHAsset) -> [String: Any?] {
return [ return [
"id": asset.localIdentifier, "id": asset.localIdentifier,
@ -459,7 +491,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
"modifiedDate": (asset.modificationDate != nil) ? NSInteger(asset.modificationDate!.timeIntervalSince1970 * 1000) : nil "modifiedDate": (asset.modificationDate != nil) ? NSInteger(asset.modificationDate!.timeIntervalSince1970 * 1000) : nil
] ]
} }
private func exportPathForAsset(asset: PHAsset, ext: String) -> URL { private func exportPathForAsset(asset: PHAsset, ext: String) -> URL {
let mediumId = asset.localIdentifier let mediumId = asset.localIdentifier
.replacingOccurrences(of: "/", with: "__") .replacingOccurrences(of: "/", with: "__")
@ -467,7 +499,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
let cachePath = self.cachePath() let cachePath = self.cachePath()
return cachePath.appendingPathComponent(mediumId + ext) return cachePath.appendingPathComponent(mediumId + ext)
} }
private func toSwiftMediumType(value: String) -> PHAssetMediaType? { private func toSwiftMediumType(value: String) -> PHAssetMediaType? {
switch value { switch value {
case "image": return PHAssetMediaType.image case "image": return PHAssetMediaType.image
@ -476,7 +508,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
default: return nil default: return nil
} }
} }
private func toDartMediumType(value: PHAssetMediaType) -> String? { private func toDartMediumType(value: PHAssetMediaType) -> String? {
switch value { switch value {
case PHAssetMediaType.image: return "image" case PHAssetMediaType.image: return "image"
@ -485,33 +517,33 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
default: return nil default: return nil
} }
} }
private func toOrientationValue(orientation: UIImage.Orientation?) -> Int { private func toOrientationValue(orientation: UIImage.Orientation?) -> Int {
guard let orientation = orientation else { guard let orientation = orientation else {
return 0 return 0
} }
switch orientation { switch orientation {
case UIImage.Orientation.up: case UIImage.Orientation.up:
return 1 return 1
case UIImage.Orientation.down: case UIImage.Orientation.down:
return 3 return 3
case UIImage.Orientation.left: case UIImage.Orientation.left:
return 6 return 6
case UIImage.Orientation.right: case UIImage.Orientation.right:
return 8 return 8
case UIImage.Orientation.upMirrored: case UIImage.Orientation.upMirrored:
return 2 return 2
case UIImage.Orientation.downMirrored: case UIImage.Orientation.downMirrored:
return 4 return 4
case UIImage.Orientation.leftMirrored: case UIImage.Orientation.leftMirrored:
return 5 return 5
case UIImage.Orientation.rightMirrored: case UIImage.Orientation.rightMirrored:
return 7 return 7
@unknown default: @unknown default:
return 0 return 0
} }
} }
private func predicateFromMediumType(mediumType: String?) -> NSPredicate? { private func predicateFromMediumType(mediumType: String?) -> NSPredicate? {
guard let type = mediumType else { guard let type = mediumType else {
return nil return nil
@ -521,41 +553,47 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
} }
return NSPredicate(format: "mediaType = %d", swiftType.rawValue) return NSPredicate(format: "mediaType = %d", swiftType.rawValue)
} }
private func extractFileExtensionFromUTI(uti: String?) -> String { private func extractFileExtensionFromUTI(uti: String?) -> String {
guard let assetUTI = uti else { guard let assetUTI = uti else {
return "" return ""
} }
guard let ext = UTTypeCopyPreferredTagWithClass(assetUTI as CFString, kUTTagClassFilenameExtension as CFString)?.takeRetainedValue() as String? else { guard let ext = UTTypeCopyPreferredTagWithClass(
assetUTI as CFString,
kUTTagClassFilenameExtension as CFString
)?.takeRetainedValue() as String? else {
return "" return ""
} }
return "." + ext return "." + ext
} }
private func extractMimeTypeFromUTI(uti: String?) -> String? { private func extractMimeTypeFromUTI(uti: String?) -> String? {
guard let assetUTI = uti else { guard let assetUTI = uti else {
return nil return nil
} }
guard let mimeType = UTTypeCopyPreferredTagWithClass(assetUTI as CFString, kUTTagClassMIMEType as CFString)?.takeRetainedValue() as String? else { guard let mimeType = UTTypeCopyPreferredTagWithClass(
assetUTI as CFString,
kUTTagClassMIMEType as CFString
)?.takeRetainedValue() as String? else {
return nil return nil
} }
return mimeType return mimeType
} }
private func extractFileExtensionFromAsset(asset: PHAsset) -> String { private func extractFileExtensionFromAsset(asset: PHAsset) -> String {
let uti = asset.value(forKey: "uniformTypeIdentifier") as? String let uti = asset.value(forKey: "uniformTypeIdentifier") as? String
return self.extractFileExtensionFromUTI(uti: uti) return self.extractFileExtensionFromUTI(uti: uti)
} }
private func extractMimeTypeFromAsset(asset: PHAsset) -> String? { private func extractMimeTypeFromAsset(asset: PHAsset) -> String? {
let uti = asset.value(forKey: "uniformTypeIdentifier") as? String let uti = asset.value(forKey: "uniformTypeIdentifier") as? String
return self.extractMimeTypeFromUTI(uti: uti) return self.extractMimeTypeFromUTI(uti: uti)
} }
private func extractFilenameFromAsset(asset: PHAsset) -> String? { private func extractFilenameFromAsset(asset: PHAsset) -> String? {
return asset.value(forKey: "originalFilename") as? String return asset.value(forKey: "originalFilename") as? String
} }
private func extractTitleFromFilename(filename: String?) -> String? { private func extractTitleFromFilename(filename: String?) -> String? {
if let name = filename { if let name = filename {
return (name as NSString).deletingPathExtension return (name as NSString).deletingPathExtension
@ -572,28 +610,28 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
} }
return nil return nil
} }
private func extractSizeFromResource(resource: PHAssetResource?) -> Int64? { private func extractSizeFromResource(resource: PHAssetResource?) -> Int64? {
if let assetResource = resource { if let assetResource = resource {
return assetResource.value(forKey: "fileSize") as? Int64 return assetResource.value(forKey: "fileSize") as? Int64
} }
return nil return nil
} }
private func cachePath() -> URL { private func cachePath() -> URL {
let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let cacheFolder = paths[0].appendingPathComponent("photo_gallery") let cacheFolder = paths[0].appendingPathComponent("photo_gallery")
try! FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil) try! FileManager.default.createDirectory(at: cacheFolder, withIntermediateDirectories: true, attributes: nil)
return cacheFolder return cacheFolder
} }
private func deleteMedium(mediumId: String, completion: @escaping (Bool, Error?) -> Void) { private func deleteMedium(mediumId: String, completion: @escaping (Bool, Error?) -> Void) {
let fetchOptions = PHFetchOptions() let fetchOptions = PHFetchOptions()
if #available(iOS 9, *) { if #available(iOS 9, *) {
fetchOptions.fetchLimit = 1 fetchOptions.fetchLimit = 1
} }
let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions) let assets: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [mediumId], options: fetchOptions)
if assets.count <= 0 { if assets.count <= 0 {
completion(false, NSError(domain: "photo_gallery", code: 404, userInfo: nil)) completion(false, NSError(domain: "photo_gallery", code: 404, userInfo: nil))
} else { } else {
@ -603,7 +641,7 @@ public class SwiftPhotoGalleryPlugin: NSObject, FlutterPlugin {
}, completionHandler: completion) }, completionHandler: completion)
} }
} }
private func cleanCache() { private func cleanCache() {
try? FileManager.default.removeItem(at: self.cachePath()) try? FileManager.default.removeItem(at: self.cachePath())
} }