用實(shí)現(xiàn)的功能: 利用UIImagePickerController
拍攝視頻贮尉、圖片块饺,并從圖庫(kù)中選擇圖片或者視頻上傳
上傳視頻:
1、獲取到本地路徑
2拙徽、轉(zhuǎn)碼成mp4格式
3刨沦、轉(zhuǎn)成NSData類型
4、填寫好的表單信息進(jìn)行上傳
需要注意的地方:使用AFN拼接表單信息的時(shí)候膘怕,第一個(gè)name是和第二個(gè)name我都給寫死了想诅,主要是自己沒弄清楚,為了一位少犯錯(cuò)岛心,我這里直接寫死了来破;第二個(gè)name要帶相應(yīng)文件格式的后綴,否則可能出錯(cuò)忘古;表單類型要和上傳的文件類型想對(duì)應(yīng)徘禁,否則可能報(bào)錯(cuò)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AFNetworking.h"
typedef NS_ENUM(NSUInteger, UpFileType) {
upFileType_image,
upFileType_video
};
@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)takePhoto:(id)sender
{
UIImagePickerController *pickVc = [[UIImagePickerController alloc] init];
pickVc.delegate = self;
pickVc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
[self presentViewController:pickVc animated:YES completion:nil];
}
- (IBAction)takeVideo:(id)sender
{
UIImagePickerController *pickVc = [[UIImagePickerController alloc] init];
pickVc.delegate = self;
pickVc.sourceType = UIImagePickerControllerSourceTypeCamera;
pickVc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
pickVc.videoQuality = UIImagePickerControllerQualityTypeMedium; //錄像質(zhì)量
pickVc.videoMaximumDuration = 600.0f; //錄像最長(zhǎng)時(shí)間
pickVc.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
[self presentViewController: pickVc animated:YES completion:nil];
}
- (IBAction)selectVideoOrPhoto:(id)sender
{
UIImagePickerController *pickVc = [[UIImagePickerController alloc] init];
pickVc.delegate = self;
pickVc.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController: pickVc animated:YES completion:nil];
}
#pragma mark - UIImagePickerController的代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
NSString *urlStr = @"https://www.xxxxxx.com/chat/files/uploadfile";
if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.movie"]){
// 視頻
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
// 獲取本地視頻url地址
NSURL *mp4 = [self convertToMp4:videoURL];
NSData *data = [NSData dataWithContentsOfURL:mp4];
NSDictionary *param = @{@"filekind":@"userintrovideo", @"filename":@"video"};
[self UpWithPOST:urlStr parameters:param data:data UpFileType:upFileType_video];
}else if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]){
UIImage *img = info[UIImagePickerControllerOriginalImage];
NSData *data = UIImageJPEGRepresentation(img, 1.0);
NSDictionary *param = @{@"filekind":@"head", @"filename":@"image"};
[self UpWithPOST:urlStr parameters:param data:data UpFileType:upFileType_image];
}
}
- (void)UpWithPOST:(NSString *)URLString
parameters:(NSDictionary *)parameters
data:(NSData *)fileData
UpFileType:(UpFileType)type //后臺(tái)給圖片服務(wù)器上起的名字
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
@"text/plain",
@"text/javascript",
@"text/json",
@"text/html",
@"image/jpeg", nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 開啟狀態(tài)欄動(dòng)畫
NSURLSessionDataTask *uploadTask = [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 注意點(diǎn): 當(dāng)傳圖片的時(shí)候,typeName是image 髓堪, mimeType是@"image/*"
// 注意點(diǎn): 當(dāng)傳視頻的時(shí)候送朱,typeName是video , mimeType是@"video/*"
// filename一般不能省略后綴干旁,比如jpg 和 mp4
NSString *typeName, *mimeType, *fileName;
if (type==upFileType_image) {
typeName = @"image";
mimeType = @"image/*";
fileName = @"fileName.jpg";
}else if (type==upFileType_video) {
typeName = @"video";
mimeType = @"video/*";
fileName = @"fileName.mp4";
}
[formData appendPartWithFileData:fileData name:typeName fileName:fileName mimeType:mimeType];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%lld--%lld",uploadProgress.totalUnitCount, uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(@"成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
[uploadTask resume];
}
// 視頻轉(zhuǎn)換為MP4
- (NSURL *)convertToMp4:(NSURL *)movUrl
{
NSURL *mp4Url = nil;
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
presetName:AVAssetExportPresetHighestQuality];
NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", [self dataPath], (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
mp4Url = [NSURL fileURLWithPath:mp4Path];
exportSession.outputURL = mp4Url;
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputFileType = AVFileTypeMPEG4;
dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed: {
NSLog(@"failed, error:%@.", exportSession.error);
} break;
case AVAssetExportSessionStatusCancelled: {
NSLog(@"cancelled.");
} break;
case AVAssetExportSessionStatusCompleted: {
NSLog(@"completed.");
} break;
default: {
NSLog(@"others.");
} break;
}
dispatch_semaphore_signal(wait);
}];
long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
if (timeout) {
NSLog(@"timeout.");
}
if (wait) {
//dispatch_release(wait);
wait = nil;
}
}
return mp4Url;
}
- (NSString*)dataPath
{
NSString *dataPath = [NSString stringWithFormat:@"%@/Library/appdata/chatbuffer", NSHomeDirectory()];
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dataPath]){
[fm createDirectoryAtPath:dataPath
withIntermediateDirectories:YES
attributes:nil
error:nil];
}
return dataPath;
}