Last active
January 5, 2021 02:11
-
-
Save artvel/0044f1dc2b13e2e22896499397319971 to your computer and use it in GitHub Desktop.
remove photo or video file in ios by the well known classic path
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
import Photos | |
extension PHAsset { | |
public static func removeAssets(_ paths: [String]){ | |
let assets = PHAsset.assetsByPaths(paths) | |
if (assets.count > 0) { | |
PHPhotoLibrary.shared().performChanges({ | |
PHAssetChangeRequest.deleteAssets(assets as NSArray) | |
}) { (result, error) in | |
// done | |
} | |
} | |
} | |
public static func assetsByPaths(_ paths:[String]) -> [PHAsset] { | |
var myPaths = paths | |
var assets: [PHAsset] = [] | |
let options = PHFetchOptions() | |
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] | |
let fetch: PHFetchResult<PHAsset> = PHAsset.fetchAssets(with: options) | |
fetch.enumerateObjects({(asset, index, boolObj) in | |
if let fname = asset.originalFilename { | |
for index in 0..<myPaths.count { | |
if myPaths[index].hasSuffix(fname) { | |
myPaths.remove(at: index) | |
assets.append(asset) | |
if myPaths.count == 0 { | |
boolObj.pointee = true | |
return | |
} | |
break | |
} | |
} | |
} | |
}) | |
return assets | |
} | |
var originalFilename: String? { | |
var fname:String? | |
if #available(iOS 9.0, *) { | |
let resources = PHAssetResource.assetResources(for: self) | |
if let resource = resources.first { | |
fname = resource.originalFilename | |
} | |
} | |
if fname == nil { | |
// this is an undocumented workaround that works as of iOS 9.1 | |
fname = self.value(forKey: "filename") as? String | |
} | |
return fname | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: