Regarding how to upload videos and pictures on iOS, let’s first clarify the ideas, and then the editor will explain the implementation process step by step according to the ideas.
Ideas:
#1. How to get pictures?
#2. How to get videos?
#3. How to save the image into the cache path?
#4. How to save videos into cache path?
#5. How to upload?
Next, we follow the above ideas step by step
First, we create a new class to store each file to be uploaded
#import <Foundation/> @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 to get pictures?
Select from the album or take a photo,
This part can be implemented using 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"); = UIImagePickerControllerSourceTypePhotoLibrary; = @[(NSString *)kUTTypeImage]; = YES; [self presentViewController: animated:YES completion:nil]; }]; UIAlertAction *cameraAction = \ [UIAlertAction actionWithTitle:@"Photograph" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog(@"Photograph"); if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { = UIImagePickerControllerSourceTypeCamera; = UIImagePickerControllerCameraCaptureModePhoto; = UIImagePickerControllerCameraDeviceRear; = YES; [self presentViewController: 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. What if you get the video?
Select from the album or shoot
This part can also be implemented using UIImagePickerController
Code:
- (void)actionVideo { UIAlertController *alertController = \ [UIAlertController alertControllerWithTitle:@"" message:@"Upload video" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *photoAction = \ [UIAlertAction actionWithTitle:@"Select from the video library" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog(@"Select from the video library"); = UIImagePickerControllerSourceTypePhotoLibrary; = @[(NSString *)kUTTypeMovie]; = NO; [self presentViewController: animated:YES completion:nil]; }]; UIAlertAction *cameraAction = \ [UIAlertAction actionWithTitle:@"Video" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { NSLog(@"Video"); = UIImagePickerControllerSourceTypeCamera; = UIImagePickerControllerCameraDeviceRear; = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]; = UIImagePickerControllerQualityType640x480; = UIImagePickerControllerCameraCaptureModeVideo; = YES; [self presentViewController: 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 cache, how to save photos into the cache directory?
In this part, we first consider the cache directory, which is generally found in Document or Temp
We create a cache directory for each picture and video:
#define PHOTOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"photoCache"] #define VIDEOCACHEPATH [NSTemporaryDirectory() stringByAppendingPathComponent:@"videoCache"]
How to save UIImage into cache:
//Save Image to cache path- (void)saveImage:(UIImage *)image toCachePath:(NSString *)path { NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:PHOTOCACHEPATH]) { NSLog(@"The path does not exist, create the path"); [fileManager createDirectoryAtPath:PHOTOCACHEPATH withIntermediateDirectories:YES attributes:nil error:nil]; } else { NSLog(@"The path exists"); } //[UIImagePNGRepresentation(image) writeToFile:path atomically:YES]; [UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES]; }
4. How to save videos into cache?
How to save videos into cache:
//Save the video to the cache path- (void)saveVideoFromPath:(NSString *)videoPath toCachePath:(NSString *)path { NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:VIDEOCACHEPATH]) { NSLog(@"The path does not exist, create the path"); [fileManager createDirectoryAtPath:VIDEOCACHEPATH withIntermediateDirectories:YES attributes:nil error:nil]; } else { NSLog(@"The path exists"); } NSError *error; [fileManager copyItemAtPath:videoPath toPath:path error:&error]; if (error) { NSLog(@"File saving to cache failed"); } }
How to get images from cache:
//Get photos from 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 usually use the current time to name the file. The method is as follows
//Synthesize the image name with 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 the video name with the 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 as display, the method is as follows:
//Get the first frame of the video and return to UIImage//Import required- (UIImage*) getVideoPreViewImageWithPath:(NSURL *)videoPath { AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil]; AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset]; = 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 is the upload method:
I dropped the server address xx, everyone can change it to your own
//Upload pictures and videos- (void)uploadImageAndMovieBaseModel:(uploadModel *)model { //Get the file's suffix name NSString *extension = [ componentsSeparatedByString:@"."].lastObject; //Set mimeType NSString *mimeType; if ([ 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 = [AFJSONResponseSerializer serializer]; //Initialize requestSerializer = [AFHTTPRequestSerializer serializer]; = nil; //Set timeout [ setTimeoutInterval:20.0]; //Set request header type [ setValue:@"form/data" forHTTPHeaderField:@"Content-Type"]; //Set request header, authorization code [ setValue:@"YgAhCMxEehT4N/DmhKkA/M0npN3KO0X8PMrNl17+hogw944GDGpzvypteMemdWb9nlzz7mk1jBa/0fpOtxeZUA==" forHTTPHeaderField:@"Authentication"]; //Upload server interface NSString *url = [NSString stringWithFormat:@""]; //Start upload [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { NSError *error; BOOL success = [formData appendPartWithFileURL:[NSURL fileURLWithPath:] name: fileName: mimeType:mimeType error:&error]; if (!success) { NSLog(@"appendPartWithFileURL error: %@", error); } } progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"Upload progress: %f", ); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"Successfully returned: %@", responseObject); = YES; [ addObject:model]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"Upload failed: %@", error); = NO; }]; }
Here are two variable arrays, uploadArray, uploadedArray, one stores the content that is about to be uploaded, and the other stores the content that has been uploaded.
What operations should be done after preparing to upload? You can check whether the number of two arrays is equal
Finally, the protocol method of UIImagePickerController
#pragma mark - UIImagePickerDelegate methods - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info { [picker dismissViewControllerAnimated:YES completion:nil]; //Get the user selects or takes photos or videos NSString *mediaType = info[UIImagePickerControllerMediaType]; if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) { //Get edited photos NSLog(@"Get the edited good movie"); UIImage *tempImage = info[UIImagePickerControllerEditedImage]; //Save photos in photo album if (tempImage) { if ( == UIImagePickerControllerSourceTypeCamera) { //Save photos in photo album NSLog(@"Save photos in album"); UIImageWriteToSavedPhotosAlbum(tempImage, self, nil, nil); } //Get the image name NSLog(@"Get the image name"); NSString *imageName = [self getImageNameBaseCurrentTime]; NSLog(@"Image Name: %@", imageName); //Save the image in cache NSLog(@"Write the image to cache"); [self saveImage:tempImage toCachePath:[PHOTOCACHEPATH stringByAppendingPathComponent:imageName]]; //Create uploadModel NSLog(@"Create a model"); uploadModel *model = [[uploadModel alloc] init]; = [PHOTOCACHEPATH stringByAppendingPathComponent:imageName]; = imageName; = @"image"; = NO; //Save the model into the array to be uploaded NSLog(@"Save Model into the array to be uploaded"); [ addObject:model]; } } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) { if ( == UIImagePickerControllerSourceTypeCamera) { //If it is a video taken, save the video in the system multimedia library NSLog(@"video path: %@", info[UIImagePickerControllerMediaURL]); ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:info[UIImagePickerControllerMediaURL] completionBlock:^(NSURL *assetURL, NSError *error) { if (!error) { NSLog(@"Video saved successfully"); } else { NSLog(@"Video Saving Failed"); } }]; } //Generate video name NSString *mediaName = [self getVideoNameBaseCurrentTime]; NSLog(@"mediaName: %@", mediaName); //Save the video into cache NSLog(@"Save videos in cache"); [self saveVideoFromPath:info[UIImagePickerControllerMediaURL] toCachePath:[VIDEOCACHEPATH stringByAppendingPathComponent:mediaName]]; //Create uploadmodel uploadModel *model = [[uploadModel alloc] init]; = [VIDEOCACHEPATH stringByAppendingPathComponent:mediaName]; = mediaName; = @"moive"; = NO; //Save the model into the array to be uploaded [ addObject:model]; } //[picker dismissViewControllerAnimated:YES completion:nil]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; }
The above is the idea of uploading videos and pictures on iOS introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!