Skip to content

Instantly share code, notes, and snippets.

@artvel
Last active January 5, 2021 02:11
Show Gist options
  • Save artvel/0044f1dc2b13e2e22896499397319971 to your computer and use it in GitHub Desktop.
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
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
}
}
@artvel
Copy link
Author

artvel commented Jan 5, 2021

Example:

PHAsset.removeAssets(["/var/mobile/Media/DCIM/100APPLE/IMG_0003.HEIC"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment