How to export PHAsset video by UIActivityViewController in iOS

后端 未结 2 923
生来不讨喜
生来不讨喜 2021-01-03 14:50

I tried to export PHAsset Video by UIActivityViewController in iOS. It worked fine when PHAsset was image. The problem was when PHAsset

2条回答
  •  北海茫月
    2021-01-03 15:06

    I have wasted a lot of time to do that.

    Finally I resolved it by saving the video to document directory, and using the file url from document directory.

    typeof(self) __weak weakSelf = self;
    
    [[PHImageManager defaultManager] requestExportSessionForVideo: self.videosAssets[index] options:nil exportPreset:AVAssetExportPresetPassthrough resultHandler:^(AVAssetExportSession *exportSession, NSDictionary *info) {
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* videoPath = [documentsDirectory stringByAppendingPathComponent:@"tempSelvi.MOV"];
        NSFileManager *manager = [NSFileManager defaultManager];
    
        NSError *error;
        if ([manager fileExistsAtPath:videoPath]) {
            BOOL success = [manager removeItemAtPath:videoPath error:&error];
            if (success) {
                NSLog(@"Already exist. Removed!");
            }
        }
    
        NSURL *outputURL = [NSURL fileURLWithPath:videoPath];
        NSLog(@"Final path %@",outputURL);
        exportSession.outputFileType=AVFileTypeQuickTimeMovie;
        exportSession.outputURL=outputURL;
    
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            if (exportSession.status == AVAssetExportSessionStatusFailed) {
                NSLog(@"failed");
            } else if(exportSession.status == AVAssetExportSessionStatusCompleted){
                NSLog(@"completed!");
                dispatch_async(dispatch_get_main_queue(), ^(void) {
                    NSArray *activityItems = [NSArray arrayWithObjects:outputURL, nil];
    
                    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
                    activityViewController.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
                        NSError *error;
                        if ([manager fileExistsAtPath:videoPath]) {
                            BOOL success = [manager removeItemAtPath:videoPath error:&error];
                            if (success) {
                                NSLog(@"Successfully removed temp video!");
                            }
                        }
                        [weakSelf dismissViewControllerAnimated:YES completion:nil];
                    };
                    [weakSelf presentViewController:activityViewController animated:YES completion:nil];
                });     
            }
        }];
    }];
    

提交回复
热议问题