iOS实现视频和图片的上传思路

2020-01-18 21:24:29于海丽

关于iOS如何实现视频和图片的上传, 我们先理清下思路,然后小编根据思路一步一步给大家详解实现过程。

思路:

#1. 如何获取图片?

#2. 如何获取视频?

#3. 如何把图片存到缓存路径中?

#4. 如何把视频存到缓存路径中?

#5. 如何上传?

接下来, 我们按照上面的思路一步一步实现

首先我们新建一个类, 用来储存每一个要上传的文件uploadModel.h


#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. 如何获取图片?

从相册选择 或者 拍照,

这部分可以用UIImagePickerController来实现


- (void)actionPhoto {
  UIAlertController *alertController = 
  [UIAlertController alertControllerWithTitle:@""
                    message:@"上传照片"
                 preferredStyle:UIAlertControllerStyleActionSheet];
  UIAlertAction *photoAction = 
  [UIAlertAction actionWithTitle:@"从相册选择"
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"从相册选择");
                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:@"拍照"
               style:UIAlertActionStyleDefault
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"拍照");
                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:@"取消"
               style:UIAlertActionStyleCancel
              handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"取消");
              }];
  [alertController addAction:photoAction];
  [alertController addAction:cameraAction];
  [alertController addAction:cancelAction];
  [self presentViewController:alertController animated:YES completion:nil];
}