使用 PhotoKit (PHAsset) 导出视频每次都会给出不同的视频文件

Exporting video using PhotoKit (PHAsset) gives different video file every time

我使用方法(这个问题的结尾)从设备中检索视频。它的作用是在库中找到第一个视频,创建导出会话并将视频导出到 MOV 文件中。

应用程序运行两 运行 秒后(在方法 运行 秒之间停止应用程序),正在比较两个生成的文件。两个文件不同。我原以为这两个文件是相同的,因为正在导出相同的资产。

再说一句:运行在同一个应用程序中调用该方法两次 运行 按预期给了我两个相同的文件。

是否可以让 PhotoKit 每次 运行s 导出同一个文件?

- (void)testVideoRetrievalSO {

    PHAsset *oneVideo = [[PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil] firstObject];

    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.networkAccessAllowed = YES;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
    options.version = PHVideoRequestOptionsVersionOriginal;


    [[PHImageManager defaultManager] requestExportSessionForVideo:oneVideo
                                                          options:options
                                                     exportPreset:AVAssetExportPresetPassthrough
                                                    resultHandler:
     ^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
         NSLog(@"Video test run on asset %@", oneVideo.localIdentifier);
         NSString *folderPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
         NSString *fileName = [[[NSUUID UUID] UUIDString] stringByAppendingPathExtension:@"mov"];
         NSString *tempFile = [folderPath stringByAppendingPathComponent:fileName];
         NSURL *tempFileUrl = [NSURL fileURLWithPath:tempFile];

         [exportSession setOutputFileType:AVFileTypeQuickTimeMovie];
         [exportSession setOutputURL:tempFileUrl];

         [exportSession exportAsynchronouslyWithCompletionHandler:^{
             NSLog(@"Video test run exported video into file: %@", tempFile);
         }];
     }];
}

已更新

不清楚,但我认为从相机胶卷导出视频并不能保证每次都获取相同的视频。所以我通过 [NSFileManager copyItemAtURL:toURL:error:] 使用 url (avurlasset.URL) 将视频从相机胶卷复制到我的文档文件夹,然后它复制相同的每次都有视频文件。现在这是我的最终解决方案。

在这种情况下,您必须使用 requestAVAssetForVideo 而不是 requestExportSessionForVideo

所以在你的情况下,

PHVideoRequestOptions *options = [PHVideoRequestOptions new];
options.version = PHVideoRequestOptionsVersionOriginal;

[[PHImageManager defaultManager] requestAVAssetForVideo:asset
                                                options:options
                                          resultHandler:
 ^(AVAsset * _Nullable avasset,
   AVAudioMix * _Nullable audioMix,
   NSDictionary * _Nullable info)
{
     NSError *error;
     AVURLAsset *avurlasset = (AVURLAsset*) avasset;

     // Write to documents folder
     NSURL *fileURL = [NSURL fileURLWithPath:tmpShareFilePath];
     if ([[NSFileManager defaultManager] copyItemAtURL:avurlasset.URL
                                                 toURL:fileURL
                                                 error:&error]) {
         NSLog(@"Copied correctly");
     }
 }];