iOS項目相關@AFN&SDWeb的二次封裝,ios項目@afn

來源:互聯網
上載者:User

iOS項目相關@AFN&SDWeb的二次封裝,ios項目@afn

一,AFNetworking跟SDWebImge是功能強大且常用的第三方,然而在實際應用中需要封裝用來複用今天就跟大家分享一下AFN&SDWeb的二次封裝

1.

HttpClient.h及.m

.h定義了HTTP常用的四種GET POST PUT DELETE 請求

一般分別用做增刪減查

定義前預先處理,請求成功處理,請求失敗處理的block

及帶多參數w的方法聲明

.m佈建要求類型跟響應類型,監聽網路是否有網路,如果沒有,彈出網路異常的警示框

2.

UIImageView+WebCache.h及.m

這是類別的方法,把網路請求圖片封裝起來

.h 定義載入成功,載入失敗及載入進度的block

下載未成功時預設圖片的載入方法及網路請求下載圖片的方法聲明

.m 

是兩個方法的具體實現

 1 #import <Foundation/Foundation.h> 2 #import "AFNetworking.h" 3  4 //HTTP請求類別 5 typedef NS_ENUM(NSInteger,HttpRequestType) { 6     HttpRequestGet, 7     HttpRequestPost, 8     HttpRequestPut, 9     HttpRequestDelete,10 };11 12 13 /**14  *  請求前預先處理block15  */16 typedef void(^PrepareExecuteBlock)(void);17 18 typedef void(^SuccessBlock)(NSURLSessionDataTask * task, id responseObject);19 20 typedef void(^FailureBlock)(NSURLSessionDataTask * task, NSError * error);21 22 @interface HttpClient : NSObject23 24 + (HttpClient *)defaultClient;25 26 /**27  *  HTTP請求(GET,POST,PUT,DELETE)28  *29  *  @param url     請求地址30  *  @param method  請求類型31  *  @param params  請求參數32  *  @param prepare 請求前預先處理33  *  @param success 請求成功處理34  *  @param failure 請求失敗處理35  */36 37 - (void)requestWithPath:(NSString *)url38                  method:(NSInteger)method39             paramenters:(NSDictionary *)params40          prepareExecute:(PrepareExecuteBlock)prepare41                 success:(SuccessBlock)success42                 failure:(FailureBlock)failure;43 44 45 @end
  1 #import "HttpClient.h"  2   3 @interface HttpClient ()  4   5 @property (nonatomic, strong) AFHTTPSessionManager * manager;  6   7 @property (nonatomic, assign) BOOL isConnect;  8   9 @end 10  11 @implementation HttpClient 12  13 - (instancetype)init 14 { 15     self = [super init]; 16     if (self) { 17          18         self.manager = [AFHTTPSessionManager manager]; 19         //佈建要求類型 20         self.manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 21         //設定響應類型 22         self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; 23          24         self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif", nil]; 25          26         //開啟監聽 27         [self openNetMonitoring]; 28          29     } 30     return self; 31 } 32  33 - (void)openNetMonitoring { 34      35     [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 36          37         switch (status) { 38             case AFNetworkReachabilityStatusUnknown: 39                 self.isConnect = NO; 40                 break; 41             case AFNetworkReachabilityStatusNotReachable: 42                 self.isConnect = NO; 43                 break; 44             case AFNetworkReachabilityStatusReachableViaWiFi: 45                 self.isConnect = YES; 46                 break; 47             case AFNetworkReachabilityStatusReachableViaWWAN: 48                 self.isConnect = YES; 49                 break; 50             default: 51                 break; 52         } 53          54     }]; 55      56     [[AFNetworkReachabilityManager sharedManager] startMonitoring]; 57      58     self.isConnect = YES; 59 } 60  61 + (HttpClient *)defaultClient { 62      63     static HttpClient * instance = nil; 64     static dispatch_once_t onceToken; 65     dispatch_once(&onceToken, ^{ 66         instance = [[self alloc] init]; 67     }); 68     return instance; 69 } 70  71 - (void)requestWithPath:(NSString *)url 72                  method:(NSInteger)method 73             paramenters:(NSDictionary *)params 74          prepareExecute:(PrepareExecuteBlock)prepare 75                 success:(SuccessBlock)success 76                 failure:(FailureBlock)failure { 77      78     NSLog(@"請求網路地址為:%@",url); 79      80     if ([self isConnectionAvailable]) { 81          82         //預先處理 83         if (prepare) { 84             prepare(); 85         } 86          87         switch (method) { 88             case HttpRequestGet: 89                 [self.manager GET:url parameters:params progress:nil success:success failure:failure]; 90                 break; 91             case HttpRequestPost: 92                 [self.manager POST:url parameters:params progress:nil success:success failure:failure]; 93                 break; 94             case HttpRequestPut: 95                 [self.manager PUT:url parameters:params success:success failure:failure]; 96                 break; 97             case HttpRequestDelete: 98                 [self.manager DELETE:url parameters:params success:success failure:failure]; 99                 break;100             default:101                 break;102         }103 104     } else {105         106         [self showExceptionDialog];107     }108 }109 110 - (BOOL)isConnectionAvailable {111     112     return self.isConnect;113 }114 115 - (void)showExceptionDialog {116     117     [[[UIAlertView alloc] initWithTitle:@"提示" message:@"網路連接異常,請檢查網路連接" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil] show];118 }119 120 @end
 1 #import <UIKit/UIKit.h> 2 #import "UIImageView+WebCache.h" 3  4 typedef void (^DownloadSuccessBlock) (SDImageCacheType cacheType, UIImage *image); 5 typedef void (^DownloadFailureBlock) (NSError *error); 6 typedef void (^DownloadProgressBlock) (CGFloat progress); 7  8 @interface UIImageView (SDWebImage) 9 10 /**11  *  SDWebImage 下載並緩衝圖片12  *13  *  @param url 圖片的url14  *15  *  @param place 還未下載成功時的替換圖片16  *17  */18 - (void)downloadImage:(NSString *)url19                 place:(UIImage *)place;20 21 /**22  *  SDWebImage 下載並緩衝圖片和下載進度23  *24  *  @param url 圖片的url25  *26  *  @param place 還未下載成功時的替換圖片27  *28  *  @param success 圖片下載成功29  *30  *  @param failure 圖片下載失敗31  *32  *  @param progress 圖片下載進度33  */34 - (void)downloadImage:(NSString *)url35                 place:(UIImage *)place36               success:(DownloadSuccessBlock)success37               failure:(DownloadFailureBlock)failure38              received:(DownloadProgressBlock)progress;39 40 41 42 @end
 1 #import "UIImageView+SDWebImage.h" 2  3 @implementation UIImageView (SDWebImage) 4  5 - (void)downloadImage:(NSString *)url 6                 place:(UIImage *)place 7 { 8     [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:place options:SDWebImageLowPriority | SDWebImageRetryFailed]; 9 }10 11 12 - (void)downloadImage:(NSString *)url13                 place:(UIImage *)place14               success:(DownloadSuccessBlock)success15               failure:(DownloadFailureBlock)failure16              received:(DownloadProgressBlock)progress17 {18     [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:place options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {19         20         progress((float)receivedSize/expectedSize);21         22     } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {23         24         if (error) {25             failure(error);26         }else{27             // image是下載好的圖片28             self.image = image;29             success(cacheType, image);30         }31     }];32 }33 34 @end

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.