-->

Upload videos from gallery using Photos framework

2020-05-24 04:06发布

问题:

What is the best way to upload videos from gallery using Photos framework? Before I used ALAssetRepresentation and next method:

- (NSUInteger)getBytes:(uint8_t *)buffer fromOffset:(long long)offset length:(NSUInteger)length error:(NSError **)error;

this allowed to upload file without first copying it to app temp directory. Don’t see any alternatives in Photos framework. Only way seems to use AVAssetExportSession -> export to local directory -> upload, but this requires additional storage space (could be a problem, if video is too big)

回答1:

Seems the only valid way is to request AVAsset from PHImageManager, and check if returned asset is AVURLAsset. In this case URL can be used to directly access file and get needed chunk of bytes:

[[PHImageManager defaultManager] requestAVAssetForVideo:videoAsset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  if ([asset isKindOfClass:[AVURLAsset class]]) {
    NSURL *URL = [(AVURLAsset *)asset URL];
    // use URL to get file content
  }
}];

This will not work with slow motion videos, because AVComposition instead of AVURLAsset is returned. Possible solution is to use PHVideoRequestOptionsVersionOriginal video file version:

PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;

[[PHImageManager defaultManager] requestAVAssetForVideo:videoAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  if ([asset isKindOfClass:[AVURLAsset class]]) {
    NSURL *URL = [(AVURLAsset *)asset URL];
    // use URL to get file content
  }
}];

And to get fullsize image url:

PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
options.canHandleAdjustmentData = ^BOOL(PHAdjustmentData *adjustmentData) {
  return YES;
};

[imageAsset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
  // use contentEditingInput.fullSizeImageURL
}];