MyZone
關(guān)于AFNetworking 3.0
NSURLConnection的API已廢棄
AFNetworking 1.0 是建立在 NSURLConnection基礎上的偿荷,AFNetworking 2.0 開始使用基于 NSURLConnection API基礎功能枝誊,同時也有基于新的NSURLSession API 的功能實現(xiàn)况芒。AFNetworking 3.0現(xiàn)在是專門建立在 NSURLSession 頂層的,這降低了維護負擔叶撒,同時允許支持蘋果為 NSURLSession 提供的任何額外的增強的特性绝骚。在Xcode 7,NSURLConnection API 已經(jīng)被蘋果官方棄用祠够。然而API函數(shù)將繼續(xù)使用不會受影響压汪,只不過再也不會添加新的功能了,蘋果建議所有基于網(wǎng)絡的功能在未來都能使用 NSURLSession古瓤。
3.0 被移除的類有
? AFURLConnectionOperation
? AFHTTPRequestOperation
? AFHTTPRequestOperationManager
轉(zhuǎn)而替代的是
? AFURLSessionManager
? AFHTTPSessionManager
下面的方法也是基于NSURLSession進行封裝的
所有的請求方法都在NetWorkManager.m
進行統(tǒng)一設置止剖,并且全部為類方法(調(diào)用方便)
tips
1.設置網(wǎng)路請求的
BaseURL
,請移步Supporting Files
-->const.h
中進行修改
#define BaseURL @"http://apis.baidu.com/apistore"
//請正確設置baseUrl的格式 否則會報無效的url(可參考demo中的設置)
2.關(guān)于tokken的設置
#warning 此處做為測試 可根據(jù)自己應用設置相應的值
/**設置apikey ------類似于自己應用中的tokken---此處僅僅作為測試使用*/
[self.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
主要實現(xiàn)的功能
1.文件下載
2.多圖壓縮上傳
3.視頻上傳(文件上傳,音頻上傳類似)
4.取消所有的網(wǎng)絡請求
5.取消指定的網(wǎng)絡請求
暫未考慮緩存請求到的數(shù)據(jù)
基本的post,get請求
/**
* 網(wǎng)絡請求的實例方法
*
* @param type get / post
* @param urlString 請求的地址
* @param paraments 請求的參數(shù)
* @param successBlock 請求成功的回調(diào)
* @param failureBlock 請求失敗的回調(diào)
* @param progress 進度
*/
+(void)requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments withSuccessBlock:( requestSuccess)successBlock withFailureBlock:( requestFailure)failureBlock progress:(downloadProgress)progress;
基本的post,get請求實現(xiàn)
/**
* 網(wǎng)絡請求的實例方法
*
* @param type get / post
* @param urlString 請求的地址
* @param paraments 請求的參數(shù)
* @param successBlock 請求成功的回調(diào)
* @param failureBlock 請求失敗的回調(diào)
* @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);
}];
}
}
}
上傳圖片
/**
* 上傳圖片
*
* @param operations 上傳圖片預留參數(shù)---視具體情況而定 可移除
* @param imageArray 上傳的圖片數(shù)組
* @parm width 圖片要被壓縮到的寬度
* @param urlString 上傳的url
* @param successBlock 上傳成功的回調(diào)
* @param failureBlock 上傳失敗的回調(diào)
* @param progress 上傳進度
*/
+(void)uploadImageWithOperations:(NSDictionary *)operations withImageArray:(NSArray *)imageArray withtargetWidth:(CGFloat )width withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress;
上傳圖片實現(xiàn)
/**
* 上傳圖片
*
* @param operations 上傳圖片等預留參數(shù)---視具體情況而定 可移除
* @param imageArray 上傳的圖片數(shù)組
* @parm width 圖片要被壓縮到的寬度
* @param urlString 上傳的url---請?zhí)顚懲暾膗rl
* @param successBlock 上傳成功的回調(diào)
* @param failureBlock 上傳失敗的回調(diào)
* @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.創(chuàng)建管理者對象
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);
}];
}
視頻上傳
/**
* 視頻上傳
*
* @param operations 上傳視頻預留參數(shù)---視具體情況而定 可移除
* @param videoPath 上傳視頻的本地沙河路徑
* @param urlString 上傳的url
* @param successBlock 成功的回調(diào)
* @param failureBlock 失敗的回調(diào)
* @param progress 上傳的進度
*/
+(void)uploadVideoWithOperaitons:(NSDictionary *)operations withVideoPath:(NSString *)videoPath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withUploadProgress:(uploadProgress)progress;
視頻上傳實現(xiàn)
/**
* 視頻上傳
*
* @param operations 上傳視頻預留參數(shù)---視具體情況而定 可移除
* @param videoPath 上傳視頻的本地沙河路徑
* @param urlString 上傳的url
* @param successBlock 成功的回調(diào)
* @param failureBlock 失敗的回調(diào)
* @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];
/**創(chuàng)建日期格式化器*/
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
/**轉(zhuǎn)化后直接寫入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) {
//獲得沙盒中的視頻內(nèi)容
[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;
}
}];
}
文件下載
#pragma mark - 文件下載
/**
* 文件下載
*
* @param operations 文件下載預留參數(shù)---視具體情況而定 可移除
* @param savePath 下載文件保存路徑
* @param urlString 請求的url
* @param successBlock 下載文件成功的回調(diào)
* @param failureBlock 下載文件失敗的回調(diào)
* @param progress 下載文件的進度顯示
*/
+(void)downLoadFileWithOperations:(NSDictionary *)operations withSavaPath:(NSString *)savePath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withDownLoadProgress:(downloadProgress)progress
文件下載實現(xiàn)
/**
* 文件下載
*
* @param operations 文件下載預留參數(shù)---視具體情況而定 可移除
* @param savePath 下載文件保存路徑
* @param urlString 請求的url
* @param successBlock 下載文件成功的回調(diào)
* @param failureBlock 下載文件失敗的回調(diào)
* @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);
}
}];
}
取消指定的url
請求
/**
* 取消指定的url請求
*
* @param requestType 該請求的請求類型
* @param string 該請求的url
*/
+(void)cancelHttpRequestWithRequestType:(NSString *)requestType requestUrlString:(NSString *)string;
取消指定的url
請求實現(xiàn)
/**
* 取消指定的url請求
*
* @param requestType 該請求的請求類型
* @param string 該請求的完整url
*/
+(void)cancelHttpRequestWithRequestType:(NSString *)requestType requestUrlString:(NSString *)string
{
NSError * error;
/**根據(jù)請求的類型 以及 請求的url創(chuàng)建一個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];
}
}
}
}
demo地址
notice
1.以上代碼僅供參考,如果有任何你覺得不對的地方,都可以聯(lián)系我,我會第一時間回復落君,謝謝.
qq:391565521
email:zhuhaifei_ios@163.com
持續(xù)完善中穿香,敬請期待.......