SoFunction
Updated on 2025-04-08

iOS video compression and storage locally and upload to server instance code

I recently made a project, and I will share the core functions with you. The key point is to sort out the key.

Here I have sorted out two methods for video transcoding storage, both of which are processed for videos in the album.

1. This method does not compress the video, but just takes the video out of the album intact and puts it under the sandbox path. The purpose is to get the NSData of the video for uploading.

Here I passed a URL. This URL is a bit special, it is the album file URL, so I said that it is only processed for album videos.

  //Convert the URL of the original video into NSData data and write it to the sandbox  + (void)videoWithUrl:(NSString *)url withFileName:(NSString *)fileName
  {
     ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
      if (url) {
       [assetLibrary assetForURL:[NSURL URLWithString:url] resultBlock:^(ALAsset *asset) {
      ALAssetRepresentation *rep = [asset defaultRepresentation];
      NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSString *imagePath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
      NSString *dbFilePath = [imagePath stringByAppendingPathComponent:fileName];
      char const *cvideoPath = [dbFilePath UTF8String];
      FILE *file = fopen(cvideoPath, "a+");
      if (file) {
        const int bufferSize = 11024 * 1024;
        // Initialize a 1M buffer        Byte *buffer = (Byte*)malloc(bufferSize);
        NSUInteger read = 0, offset = 0, written = 0;
        NSError* err = nil;
        if ( != 0)
        {
          do {
            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
            written = fwrite(buffer, sizeof(char), read, file);
            offset += read;
          } while (read != 0 && !err);//Not to the end, no error, OK to continue        }
        // Release the buffer and close the file        free(buffer);
        buffer = NULL;
        fclose(file);
        file = NULL;
      }
    } failureBlock:nil];
  }
});
}

2. It is recommended to use this method, which compresses the video, and the degree of compression is adjustable.

Here I am passing the model, bringing my URL, and then using the model to bring out the NSData. Everyone can freely use the data according to their needs.

+ (void) convertVideoWithModel:(RZProjectFileModel *) model
{
   = [NSString stringWithFormat:@"%ld.mp4",RandomNum];
  //Save to sandbox path  NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *videoPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
   = [videoPath stringByAppendingPathComponent:];

  //Transcoding configuration  AVURLAsset *asset = [AVURLAsset URLAssetWithURL: options:nil];
  AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
   = YES;
   = [NSURL fileURLWithPath:];
   = AVFileTypeMPEG4;
  [exportSession exportAsynchronouslyWithCompletionHandler:^{
     int exportStatus = ;
    RZLog(@"%d",exportStatus);
    switch (exportStatus)
    {
      case AVAssetExportSessionStatusFailed:
      {
        // log error to text view
        NSError *exportError = ;
        NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
        break;
      }
      case AVAssetExportSessionStatusCompleted:
      {
        RZLog(@"Video transcoding successfully");
        NSData *data = [NSData dataWithContentsOfFile:];
         = data;
      }
    }
    }];

}

Here you can modify the compression ratio. Apple has officially packaged it and adjusted according to your needs.

AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];

Change the output type here. Under normal circumstances, there will be no problem with choosing MP4.

 = AVFileTypeMPEG4;

Mark this for image compression. Image is the picture, 0.4 is the scale, and the size is adjustable.

 = UIImageJPEGRepresentation(image, 0.4);

In this way, you will get the NSData after the transcoding happily, and then play it and try it

 MPMoviePlayerViewController* playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:sandBoxFilePath]];
[superVC presentViewController:playerView animated:YES completion:nil];

Note

You can find that I use sandbox storage here. In the next section, I will sort out the application sandbox using code management.

renew

Recently I found that many people contacted me and asked me for a demo. I have sorted it out recently. It is currently on github. I hope the masters will correct me.

/Snoopy008/SelectVideoAndConvert

2017-3-23

I accidentally helped a friend read the code and found a simpler method to get NSData for local videos. Everyone can watch it for themselves, so I won’t explain it. Put the code on github/Snoopy008/videoData

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.