iOS开发--删除本地相册照片

    void (^completionHandler)(BOOL, NSError *) = ^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"delete success");
        } else {
            NSLog(@"Error: %@", error);
        }
    };
    
    NSString *currentPhotoPath = @"照片的路径";
    NSURL *photoUrl = [[NSURL alloc] initWithString:currentPhotoPath];
    NSArray *urlArray = [[NSArray alloc] initWithObjects:photoUrl, nil];
    PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:urlArray options:nil];
    if (result) {
        PHAsset *asset = [result lastObject];
        if (asset) {
            NSArray *delAssets = [[NSArray alloc] initWithObjects:asset, nil];
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [PHAssetChangeRequest deleteAssets:delAssets];
            } completionHandler:completionHandler];
        }
    }

 iOS 8.0以上才支持删除本地照片,8.0版本以下只支持删除app自身创建的照片。使用之前,请导入Photos.framework。


如果要兼容8.0以下的系统,代码则要这么写:

    Class PHPhotoLibrary_Class = NSClassFromString(@"PHPhotoLibrary");
    if (PHPhotoLibrary_Class) { //iOS8.x 删除本地照片
        //动态获取所使用到的Class
        Class phAssetClass = NSClassFromString(@"PHAsset");
        Class phAssetChangeRequestClass = NSClassFromString(@"PHAssetChangeRequest");
        SEL fetchAssetsSel = NSSelectorFromString(@"fetchAssetsWithALAssetURLs:options:");
        SEL deleteAssetsSel = NSSelectorFromString(@"deleteAssets:");
        
        // 在此删除照片

    }else{
        NSLog(@"iOS 8.0以下,不支持删除iPhone中照片");
    }
注意这里要使用opitional方式导入Photos.framework




你可能感兴趣的:(iOS开发--删除本地相册照片)