使用PHPhotoLibrary API保存大量文件时出现异常

M.M*_*asa 7 exception objective-c ios phphotolibrary

我的应用程序具有在tmp文件夹中下载许多照片和视频文件的功能,并使用PHPhotoLibrary API将它们保存在相机胶卷中.

问题是有时(概率大约为10%)异常发生在保存过程中.

控制台中的错误消息是,

由于未捕获的异常'NSInternalInconsistencyException'终止应用程序,原因:'此方法只能从 - [PHPhotoLibrary performChanges:completionHandler:]或 - [PHPhotoLibrary performChangesAndWait:error:]'内部调用

我的代码如下:

- (void)saveVideoFileInCameraRoll:(NSString *)videoFilePath
{
    NSURL *videoFileUrl = [NSURL fileURLWithPath:videoFilePath];

    photoLibrarySaveImageCompletion completion = ^(BOOL success, NSError *error) {
        NSLog(@"success=%@, error=%@", (success ? @"YES" : @"NO"), error);
    };

    NSLog(@"videoFileUrl=%@", videoFileUrl);

    [self saveVideoFile:videoFileUrl completion:completion];
}

- (void)saveVideoFile:(NSURL *)fileURL completion:(photoLibrarySaveImageCompletion)completion
{
    NSLog(@"fileURL=%@", fileURL);

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        NSLog(@"fileURL=%@", fileURL);

        // Exception happens on this line as [SIGABRT]
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileURL]; 

        if (_assetCollection) {
            PHAssetCollectionChangeRequest *assetCollectionChangeRequest =
                [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.assetCollection];
            [assetCollectionChangeRequest addAssets:@[ [assetChangeRequest placeholderForCreatedAsset] ]];
        }
        else {
            NSLog(@"### assetCollection is nil ###");
        }
    }

        completionHandler:^(BOOL success, NSError *_Nullable error) {
            NSLog(@"success=%@, error=%@", (success ? @"YES" : @"NO"), error);

            completion(success, error);
        }];
}
Run Code Online (Sandbox Code Playgroud)

我检查了类似的情况:

使用照片框架将图像保存到照片库

案件每次都崩溃,但我的代码很少崩溃.

而且与我打电话的情况不同

[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:]
Run Code Online (Sandbox Code Playgroud)

'performChanges'街区

另外我通过NSLog在tmp文件夹中确认了视频文件的fileURL,并且在'performChanges'块的外部和内部都可以.

fileURL =文件:///private/var/mobile/Containers/Data/Application/C87F0F75-E128-4E9F-AE07-6B914939AC5D/tmp/video3.mp4

如果您能告诉我这个问题的原因或解决方法,我将不胜感激.