AFN3.0API调用

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

3.0 被移除的类有
• AFURLConnectionOperation • AFHTTPRequestOperation • AFHTTPRequestOperationManager

转而替代的是
• AFURLSessionManager • AFHTTPSessionManager
下面的方法也是基于NSURLSession进行封装的 所有的请求方法都在NetWorkManager.m进行统一设置,并且全部为类方法(调用方便)
主要实现的功能
1.文件下载 2.多图压缩上传 3.视频上传(文件上传,音频上传类似) 4.取消所有的网络请求 5.取消指定的网络请求
暂未考虑缓存请求到的数据

干货来了:
1----->基本的post,get请求--->.h
/**
 *  网络请求的实例方法
 *
 *  @param type         get / post
 *  @param urlString    请求的地址
 *  @param paraments    请求的参数
 *  @param successBlock 请求成功的回调
 *  @param failureBlock 请求失败的回调
 *  @param progress 进度
 */
+(void)requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments withSuccessBlock:( requestSuccess)successBlock withFailureBlock:( requestFailure)failureBlock progress:(downloadProgress)progress;
基本的post,get请求实现---->.m
/**
 *  网络请求的实例方法
 *
 *  @param type         get / post
 *  @param urlString    请求的地址
 *  @param paraments    请求的参数
 *  @param successBlock 请求成功的回调
 *  @param failureBlock 请求失败的回调
 *  @param progress 进度
 */
 
+(void)requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(downloadProgress)progress
{
 
 
    switch (type) {
 
        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(error);
            }];
 
            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(error);
 
            }];
        }
 
    }
 
}


2----->上传图片
.h
/**
 *  上传图片
 *
 *  @param operations   上传图片预留参数---视具体情况而定 可移除
 *  @param imageArray   上传的图片数组
 *  @parm width      图片要被压缩到的宽度
 *  @param urlString    上传的url
 *  @param successBlock 上传成功的回调
 *  @param failureBlock 上传失败的回调
 *  @param progress     上传进度
 */
 
+(void)uploadImageWithOperations:(NSDictionary *)operations withImageArray:(NSArray *)imageArray withtargetWidth:(CGFloat )width withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress;
.m
/**
 *  上传图片
 *
 *  @param operations   上传图片等预留参数---视具体情况而定 可移除
 *  @param imageArray   上传的图片数组
 *  @parm width      图片要被压缩到的宽度
 *  @param urlString    上传的url---请填写完整的url
 *  @param successBlock 上传成功的回调
 *  @param failureBlock 上传失败的回调
 *  @param progress     上传进度
 *
 */
+(void)uploadImageWithOperations:(NSDictionary *)operations withImageArray:(NSArray *)imageArray withtargetWidth:(CGFloat )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",(long)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(error);
 
    }];
}

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

.m
/**
 *  视频上传
 *
 *  @param operations   上传视频预留参数---视具体情况而定 可移除
 *  @param videoPath    上传视频的本地沙河路径
 *  @param urlString     上传的url
 *  @param successBlock 成功的回调
 *  @param failureBlock 失败的回调
 *  @param progress     上传的进度
 */
 
+(void)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(error);
 
                }];
 
                break;
            }
            default:
                break;
        }
 
 
    }];
 
}

4----->文件下载
.h
/**
 *  文件下载
 *
 *  @param operations   文件下载预留参数---视具体情况而定 可移除
 *  @param savePath     下载文件保存路径
 *  @param urlString        请求的url
 *  @param successBlock 下载文件成功的回调
 *  @param failureBlock 下载文件失败的回调
 *  @param progress     下载文件的进度显示
 */
 
+(void)downLoadFileWithOperations:(NSDictionary *)operations withSavaPath:(NSString *)savePath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withDownLoadProgress:(downloadProgress)progress

.m
/**
 *  文件下载
 *
 *  @param operations   文件下载预留参数---视具体情况而定 可移除
 *  @param savePath     下载文件保存路径
 *  @param urlString        请求的url
 *  @param successBlock 下载文件成功的回调
 *  @param failureBlock 下载文件失败的回调
 *  @param progress     下载文件的进度显示
 */
 
+(void)downLoadFileWithOperations:(NSDictionary *)operations withSavaPath:(NSString *)savePath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withDownLoadProgress:(downloadProgress)progress
{
 
 
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
 
 
    [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:^(NSProgress * _Nonnull downloadProgress) {
 
        progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
 
 
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
 
                return  [NSURL URLWithString:savePath];
 
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
 
        if (error) {
 
            failureBlock(error);
        }
 
    }];
 
}

5---->取消指定的url请求
.h
/**
 *  取消指定的url请求
 *
 *  @param requestType 该请求的请求类型
 *  @param string      该请求的url
 */
 
+(void)cancelHttpRequestWithRequestType:(NSString *)requestType requestUrlString:(NSString *)string;
.m
/**
 *  取消指定的url请求
 *
 *  @param requestType 该请求的请求类型
 *  @param string      该请求的完整url
 */
 
+(void)cancelHttpRequestWithRequestType:(NSString *)requestType requestUrlString:(NSString *)string
{
 
    NSError * error;
 
    /**根据请求的类型 以及 请求的url创建一个NSMutableURLRequest---通过该url去匹配请求队列中是否有该url,如果有的话 那么就取消该请求*/
 
    NSString * urlToPeCanced = [[[[NetWorkManager shareManager].requestSerializer requestWithMethod:requestType URLString:string parameters:nil error:&error] URL] path];
 
 
    for (NSOperation * operation in [NetWorkManager shareManager].operationQueue.operations) {
 
        //如果是请求队列
        if ([operation isKindOfClass:[NSURLSessionTask class]]) {
 
            //请求的类型匹配
            BOOL hasMatchRequestType = [requestType isEqualToString:[[(NSURLSessionTask *)operation currentRequest] HTTPMethod]];
 
            //请求的url匹配
 
            BOOL hasMatchRequestUrlString = [urlToPeCanced isEqualToString:[[[(NSURLSessionTask *)operation currentRequest] URL] path]];
 
            //两项都匹配的话  取消该请求
            if (hasMatchRequestType&&hasMatchRequestUrlString) {
 
                [operation cancel];
 
            }
        }
 
    }
}

参考网址:http://code4app.com/thread-8424-1-1.html




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值