AFNetworking下载文件和文件上传

来源:http://www.sh-fengwen.com 作者:鲜果干果 人气:198 发布时间:2019-09-11
摘要:ifought,but i lost,then i rest - (void)downLoad{ My carrd url My github url My csdn url     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSURLConnection的API已废弃 AFNetworking 1.0 是建立在 NSURLConnection 基础上

图片 1i fought,but i lost,then i rest

- (void)downLoad{

  • My carrd url
  • My github url
  • My csdn url

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSURLConnection的API已废弃

AFNetworking 1.0 是建立在 NSURLConnection基础上的,AFNetworking 2.0 开始使用基于 NSURLConnectionAPI基础功能,同时也有基于新的NSURLSession API 的功能实现。AFNetworking 3.0现在是专门建立在 NSURLSession 顶层的,这降低了维护负担,同时允许支持苹果为 NSURLSession 提供的任何额外的增强的特性。在Xcode 7NSURLConnection API 已经被苹果官方弃用。然而API函数将继续使用不会受影响,只不过再也不会添加新的功能了,苹果建议所有基于网络的功能在未来都能使用 NSURLSession

    //2.创建请求对象

3.0 被移除的类有

• AFURLConnectionOperation• AFHTTPRequestOperation• AFHTTPRequestOperationManager

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"];

转而替代的是

• AFURLSessionManager• AFHTTPSessionManager

下面的方法也是基于NSURLSession进行封装的所有的请求方法都在NetWorkManager.m进行统一设置,并且全部为类方法

1.设置网路请求的BaseURL,请移步Supporting Files-->const.h中进行修改

 #define BaseURL @"http://apis.baidu.com/apistore" //请正确设置baseUrl的格式 否则会报无效的url(可参考demo中的设置)

2.关于tokken的设置

 #warning 此处做为测试 可根据自己应用设置相应的值 /**设置apikey ------类似于自己应用中的tokken---此处仅仅作为测试使用*/ [self.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];

1.文件下载2.多图压缩上传3.视频上传(文件上传,音频上传类似)4.取消所有的网络请求5.取消指定的网络请求暂未考虑缓存请求到的数据

   //3.创建下载请求任务

基本的post,get请求

/** * 网络请求的实例方法 * * @param type get / post * @param urlString 请求的地址 * @param paraments 请求的参数 * @param successBlock 请求成功的回调 * @param failureBlock 请求失败的回调 * @param progress 进度 */+requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:paraments withSuccessBlock:( requestSuccess)successBlock withFailureBlock:( requestFailure)failureBlock progress:(downloadProgress)progress; 

    /*

基本的post,get请求实现

/** * 网络请求的实例方法 * * @param type get / post * @param urlString 请求的地址 * @param paraments 请求的参数 * @param successBlock 请求成功的回调 * @param failureBlock 请求失败的回调 * @param progress 进度 */+requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:paraments withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(downloadProgress)progress{ switch  { case HttpRequestTypeGet: { [[NetWorkManager shareManager] GET:urlString parameters:paraments progress:^(NSProgress * _Nonnull downloadProgress) { progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { successBlock(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failureBlock; }]; break; } case HttpRequestTypePost: { [[NetWorkManager shareManager] POST:urlString parameters:paraments progress:^(NSProgress * _Nonnull uploadProgress) { progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { successBlock(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failureBlock; }]; } } }

     *第一个参数: 请求对象

上传图片

/** * 上传图片 * * @param operations 上传图片预留参数---视具体情况而定 可移除 * @param imageArray 上传的图片数组 * @parm width 图片要被压缩到的宽度 * @param urlString 上传的url * @param successBlock 上传成功的回调 * @param failureBlock 上传失败的回调 * @param progress 上传进度 */+uploadImageWithOperations:(NSDictionary *)operations withImageArray:(NSArray *)imageArray withtargetWidth:width withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress;

     *第二个参数:progress 进度回调

上传图片实现

/** * 上传图片 * * @param operations 上传图片等预留参数---视具体情况而定 可移除 * @param imageArray 上传的图片数组 * @parm width 图片要被压缩到的宽度 * @param urlString 上传的url---请填写完整的url * @param successBlock 上传成功的回调 * @param failureBlock 上传失败的回调 * @param progress 上传进度 * */+uploadImageWithOperations:(NSDictionary *)operations withImageArray:(NSArray *)imageArray withtargetWidth:width withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress;{ //1.创建管理者对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager POST:urlString parameters:operations constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { NSUInteger i = 0 ; /**出于性能考虑,将上传图片进行压缩*/ for (UIImage * image in imageArray) { //image的分类方法 UIImage * resizedImage = [UIImage IMGCompressed:image targetWidth:width]; NSData * imgData = UIImageJPEGRepresentation(resizedImage, .5); //拼接data [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",i] fileName:@"image.png" mimeType:@" image/jpeg"]; i++; } } progress:^(NSProgress * _Nonnull uploadProgress) { progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) { successBlock(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failureBlock; }];}

     *第三个参数:destination 需要在该回调中告诉方法应该把下载的文件保存带哪里

视频上传

/** * 视频上传 * * @param operations 上传视频预留参数---视具体情况而定 可移除 * @param videoPath 上传视频的本地沙河路径 * @param urlString 上传的url * @param successBlock 成功的回调 * @param failureBlock 失败的回调 * @param progress 上传的进度 */+uploadVideoWithOperaitons:(NSDictionary *)operations withVideoPath:(NSString *)videoPath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withUploadProgress:(uploadProgress)progress;

        targetPath:临时存放路径(默认写入的)

视频上传实现

/** * 视频上传 * * @param operations 上传视频预留参数---视具体情况而定 可移除 * @param videoPath 上传视频的本地沙河路径 * @param urlString 上传的url * @param successBlock 成功的回调 * @param failureBlock 失败的回调 * @param progress 上传的进度 */+uploadVideoWithOperaitons:(NSDictionary *)operations withVideoPath:(NSString *)videoPath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withUploadProgress:(uploadProgress)progress{ /**获得视频资源*/ AVURLAsset * avAsset = [AVURLAsset assetWithURL:[NSURL URLWithString:videoPath]]; /**压缩*/ // NSString *const AVAssetExportPreset640x480;// NSString *const AVAssetExportPreset960x540;// NSString *const AVAssetExportPreset1280x720;// NSString *const AVAssetExportPreset1920x1080;// NSString *const AVAssetExportPreset3840x2160; AVAssetExportSession * avAssetExport = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPreset640x480]; /**创建日期格式化器*/ NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"]; /**转化后直接写入Library---caches*/ NSString * videoWritePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:[NSString stringWithFormat:@"/output-%@.mp4",[formatter stringFromDate:[NSDate date]]]]; avAssetExport.outputURL = [NSURL URLWithString:videoWritePath]; avAssetExport.outputFileType = AVFileTypeMPEG4; [avAssetExport exportAsynchronouslyWithCompletionHandler:^{ switch ([avAssetExport status]) { case AVAssetExportSessionStatusCompleted: { AFHTTPSessionManager * manager = [AFHTTPSessionManager manager]; [manager POST:urlString parameters:operations constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { //获得沙盒中的视频内容 [formData appendPartWithFileURL:[NSURL fileURLWithPath:videoWritePath] name:@"write you want to writre" fileName:videoWritePath mimeType:@"video/mpeg4" error:nil]; } progress:^(NSProgress * _Nonnull uploadProgress) { progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) { successBlock(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failureBlock; }]; break; } default: break; } }];}

        response:响应头信息

本文由美高梅游戏平台网站发布于鲜果干果,转载请注明出处:AFNetworking下载文件和文件上传

关键词:

上一篇:iOS开发 关于处理网络请求返回的数据

下一篇:没有了

最火资讯