Idea of uploading video and picture by iOS

  • 2021-11-13 18:27:59
  • OfStack

About iOS how to realize the upload of video and pictures, we first clarify the next ideas, and then this site gives you a detailed explanation of the implementation process according to the ideas step by step.

Thoughts:

# 1. How do I get a picture?

# 2. How do I get my video?

# 3. How do I save my picture to the cache path?

# 4. How do I save my video to the cache path?

# 5. How to upload?

Next, we follow the above idea step by step

First, we create a new class to store every file uploadModel. h to upload


#import <Foundation/Foundation.h>
@interface uploadModel : NSObject
@property (nonatomic, strong) NSString *path;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) BOOL   isUploaded;
@end

# 1. How do I get a picture?

Choose or take pictures from photo albums,

This part can be implemented with UIImagePickerController

The code is as follows:


- (void)actionPhoto {
  UIAlertController *alertController = \
  [UIAlertController alertControllerWithTitle:@""
                    message:@" Upload photos "
                 preferredStyle:UIAlertControllerStyleActionSheet];
  UIAlertAction *photoAction = \
  [UIAlertAction actionWithTitle:@" Select from Album "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Select from Album ");
                self.imagePicker.sourceType  = UIImagePickerControllerSourceTypePhotoLibrary;
                self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
                self.imagePicker.allowsEditing = YES;
                [self presentViewController:self.imagePicker
                         animated:YES
                        completion:nil];
              }];
  UIAlertAction *cameraAction = \
  [UIAlertAction actionWithTitle:@" Photographing "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Photographing ");
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                  self.imagePicker.sourceType    = UIImagePickerControllerSourceTypeCamera;
                  self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                  self.imagePicker.cameraDevice   = UIImagePickerControllerCameraDeviceRear;
                  self.imagePicker.allowsEditing   = YES;
                  [self presentViewController:self.imagePicker
                           animated:YES
                          completion:nil];
                }
              }];
  UIAlertAction *cancelAction = \
  [UIAlertAction actionWithTitle:@" Cancel "
               style:UIAlertActionStyleCancel
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Cancel ");
              }];
  [alertController addAction:photoAction];
  [alertController addAction:cameraAction];
  [alertController addAction:cancelAction];
  [self presentViewController:alertController animated:YES completion:nil];
}

# 2. If you get video?

Choose or shoot from the album

This part can also be implemented with UIImagePickerController

Code:


- (void)actionVideo {
  UIAlertController *alertController = \
  [UIAlertController alertControllerWithTitle:@""
                    message:@" Upload video "
                 preferredStyle:UIAlertControllerStyleActionSheet];
  UIAlertAction *photoAction = \
  [UIAlertAction actionWithTitle:@" Select from a video library "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Select from a video library ");
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
                self.imagePicker.allowsEditing = NO;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
              }];
  UIAlertAction *cameraAction = \
  [UIAlertAction actionWithTitle:@" Video recording "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Video recording ");
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                self.imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
                self.imagePicker.videoQuality = UIImagePickerControllerQualityType640x480;
                self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
                self.imagePicker.allowsEditing = YES;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
              }];
  UIAlertAction *cancelAction = \
  [UIAlertAction actionWithTitle:@" Cancel "
               style:UIAlertActionStyleCancel
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Cancel ");
              }];
  [alertController addAction:photoAction];
  [alertController addAction:cameraAction];
  [alertController addAction:cancelAction];
  [self presentViewController:alertController animated:YES completion:nil];
}

# 3. About caching, how to store photos in the cache directory?

In this part, we first consider the cache directory, which generally exists in Document or Temp

We create a cache directory for pictures and videos:


#define PHOTOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"photoCache"]
#define VIDEOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"videoCache"]

The method of storing UIImage in cache:


// Will Image Save to cache path 
- (void)saveImage:(UIImage *)image toCachePath:(NSString *)path {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if (![fileManager fileExistsAtPath:PHOTOCACHEPATH]) {
    NSLog(@" Path does not exist ,  Create path ");
    [fileManager createDirectoryAtPath:PHOTOCACHEPATH
        withIntermediateDirectories:YES
                attributes:nil
                   error:nil];
  } else {
    NSLog(@" Path existence ");
  }
  //[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
  [UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES];
}

4. How to store video in cache?

The method of storing video in cache:


// Save video to cache path 
- (void)saveVideoFromPath:(NSString *)videoPath toCachePath:(NSString *)path {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if (![fileManager fileExistsAtPath:VIDEOCACHEPATH]) {
    NSLog(@" Path does not exist ,  Create path ");
    [fileManager createDirectoryAtPath:VIDEOCACHEPATH
        withIntermediateDirectories:YES
                attributes:nil
                   error:nil];
  } else {
    NSLog(@" Path existence ");
  }
  NSError *error;
  [fileManager copyItemAtPath:videoPath toPath:path error:&error];
  if (error) {
    NSLog(@" Failed to save file to cache ");
  }
}

How to get pictures from cache:


// Get photos from the cache path 
- (UIImage *)getImageFromPath:(NSString *)path {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  if ([fileManager fileExistsAtPath:path]) {
    return [UIImage imageWithContentsOfFile:path];
  }
  return nil;
}

When uploading pictures and videos, we will generally use the current time to name the file as follows


// Synthesize picture names at the current time 
- (NSString *)getImageNameBaseCurrentTime {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
  return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".JPG"];
}
// Synthesize video names at current time 
- (NSString *)getVideoNameBaseCurrentTime {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
  return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".MOV"];
}

Sometimes you need to get the first frame of the video for display, as follows:


// Gets the first of the video 1 Frame screenshot ,  Return UIImage
// Import is required AVFoundation.h
- (UIImage*) getVideoPreViewImageWithPath:(NSURL *)videoPath
{
  AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];
  AVAssetImageGenerator *gen     = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  gen.appliesPreferredTrackTransform = YES;
  CMTime time   = CMTimeMakeWithSeconds(0.0, 600);
  NSError *error  = nil;
  CMTime actualTime;
  CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
  UIImage *img   = [[UIImage alloc] initWithCGImage:image];
  return img;
}

5. How to upload?

Here's how to upload:

I dropped the server address xx, so you can change it to your own


// Upload pictures and videos 
- (void)uploadImageAndMovieBaseModel:(uploadModel *)model {
  // Gets the suffix name of the file 
  NSString *extension = [model.name componentsSeparatedByString:@"."].lastObject;
  // Settings mimeType
  NSString *mimeType;
  if ([model.type isEqualToString:@"image"]) {
    mimeType = [NSString stringWithFormat:@"image/%@", extension];
  } else {
    mimeType = [NSString stringWithFormat:@"video/%@", extension];
  }
  // Create AFHTTPSessionManager
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  // Set the response file type to JSON Type 
  manager.responseSerializer  = [AFJSONResponseSerializer serializer];
  // Initialization requestSerializer
  manager.requestSerializer   = [AFHTTPRequestSerializer serializer];
  manager.responseSerializer.acceptableContentTypes = nil;
  // Settings timeout
  [manager.requestSerializer setTimeoutInterval:20.0];
  // Set the request header type 
  [manager.requestSerializer setValue:@"form/data" forHTTPHeaderField:@"Content-Type"];
  // Set the request header ,  Authorization code 
  [manager.requestSerializer setValue:@"YgAhCMxEehT4N/DmhKkA/M0npN3KO0X8PMrNl17+hogw944GDGpzvypteMemdWb9nlzz7mk1jBa/0fpOtxeZUA==" forHTTPHeaderField:@"Authentication"];
  // Upload server interface 
  NSString *url = [NSString stringWithFormat:@"http://xxxxx.xxxx.xxx.xx.x"];
  // Start uploading 
  [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
    NSError *error;
    BOOL success = [formData appendPartWithFileURL:[NSURL fileURLWithPath:model.path] name:model.name fileName:model.name mimeType:mimeType error:&error];
    if (!success) {
      NSLog(@"appendPartWithFileURL error: %@", error);
    }
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@" Upload progress : %f", uploadProgress.fractionCompleted);
  } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    NSLog(@" Successful return : %@", responseObject);
    model.isUploaded = YES;
    [self.uploadedArray addObject:model];
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@" Upload failed : %@", error);
    model.isUploaded = NO;
  }];
}

There are two variable arrays uploadArray and uploadedArray created in advance, one storing the content to be uploaded and the other storing the uploaded content

What do you do after you are ready to upload? You can check whether the number of two arrays is equal

Finally, the protocol method of UIImagePickerController


- (void)actionPhoto {
  UIAlertController *alertController = \
  [UIAlertController alertControllerWithTitle:@""
                    message:@" Upload photos "
                 preferredStyle:UIAlertControllerStyleActionSheet];
  UIAlertAction *photoAction = \
  [UIAlertAction actionWithTitle:@" Select from Album "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Select from Album ");
                self.imagePicker.sourceType  = UIImagePickerControllerSourceTypePhotoLibrary;
                self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
                self.imagePicker.allowsEditing = YES;
                [self presentViewController:self.imagePicker
                         animated:YES
                        completion:nil];
              }];
  UIAlertAction *cameraAction = \
  [UIAlertAction actionWithTitle:@" Photographing "
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Photographing ");
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                  self.imagePicker.sourceType    = UIImagePickerControllerSourceTypeCamera;
                  self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                  self.imagePicker.cameraDevice   = UIImagePickerControllerCameraDeviceRear;
                  self.imagePicker.allowsEditing   = YES;
                  [self presentViewController:self.imagePicker
                           animated:YES
                          completion:nil];
                }
              }];
  UIAlertAction *cancelAction = \
  [UIAlertAction actionWithTitle:@" Cancel "
               style:UIAlertActionStyleCancel
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@" Cancel ");
              }];
  [alertController addAction:photoAction];
  [alertController addAction:cameraAction];
  [alertController addAction:cancelAction];
  [self presentViewController:alertController animated:YES completion:nil];
}
0

Related articles: