利用AFN上傳圖片和視頻

用實(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;
}

demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末驶沼,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子争群,更是在濱河造成了極大的恐慌回怜,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件换薄,死亡現(xiàn)場(chǎng)離奇詭異玉雾,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)轻要,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門复旬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人伦腐,你說我怎么就攤上這事赢底。” “怎么了柏蘑?”我有些...
    開封第一講書人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵幸冻,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我咳焚,道長(zhǎng)洽损,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任革半,我火速辦了婚禮碑定,結(jié)果婚禮上流码,老公的妹妹穿的比我還像新娘。我一直安慰自己延刘,他們只是感情好漫试,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著碘赖,像睡著了一般驾荣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上普泡,一...
    開封第一講書人閱讀 51,155評(píng)論 1 299
  • 那天播掷,我揣著相機(jī)與錄音,去河邊找鬼撼班。 笑死歧匈,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的砰嘁。 我是一名探鬼主播件炉,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼矮湘!你這毒婦竟也來了妻率?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎怔匣,沒想到半個(gè)月后怖侦,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡谴餐,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片橘洞。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖说搅,靈堂內(nèi)的尸體忽然破棺而出炸枣,到底是詐尸還是另有隱情,我是刑警寧澤弄唧,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布适肠,位于F島的核電站,受9級(jí)特大地震影響候引,放射性物質(zhì)發(fā)生泄漏侯养。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一澄干、第九天 我趴在偏房一處隱蔽的房頂上張望逛揩。 院中可真熱鬧柠傍,春花似錦、人聲如沸辩稽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逞泄。三九已至患整,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間炭懊,已是汗流浹背并级。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留侮腹,地道東北人嘲碧。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像父阻,于是被迫代替她去往敵國(guó)和親愈涩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容