AFNetworking 3.1

來源:互聯網
上載者:User

標籤:

聽說之後AFHttpWorking版本可能會影響到蘋果的審核,今天下了最新版本的AFHttpWorking,並且做了簡單的封裝,我這裡是通過cocoapods下載了兩個工具

1=AFHttpWorking  2=JSONKit  為什麼要下jsonkit勒,以前json解析都使用touchjson,偶然發現資料說jsonkit效率是第三方json解析中最高的,所以今天把它也下了來下,我這裡只做了AFHttpWorking 的get/post/網路判斷三個方法。下面我貼代碼

 

.h檔案

 

#import <Foundation/Foundation.h>#import "AFDataDefine.h"#import <AFNetworking/AFNetworking.h>static NSString* const  [email protected]"http://www.xx.com";@interface APIClient : AFHTTPSessionManager+ (APIClient *)sharedClient;-(void)getUrl:(NSString *)URLString parameters:(id)parameters call:(void (^)( RespInfo* info))callback;-(void)postUrl:(NSString *)URLString parameters:(id)parameters call:(void (^)( RespInfo* info))callback;-(void)checkNetWorkingIsOrNoUse:  (void (^)(  int  StateOrType))callback;@end

 

 .m檔案

#import "APIClient.h"#import <JSONKit/JSONKit.h>#pragma mark -@implementation APIClient+ (instancetype)sharedClient {    static APIClient *_sharedClient = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _sharedClient = [[APIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFAppDotNetAPIBaseURLString]];        _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];         _sharedClient.requestSerializer.timeoutInterval =20;            });        _sharedClient.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"text/plain",@"charset=UTF-8",@"Content-Type",@"application/json",nil];;        return _sharedClient;}#pragma mark -/** *  網路監測(在什麼網路狀態) * *  @callback 1          未知網路 *  @callback 2        無網路 *  @callback 3 蜂窩資料網 *  @callback 4 WiFi網路 */-(void)checkNetWorkingIsOrNoUse:  (void (^)(  int  StateOrType))callback{    // 建立網路監測者       [ [AFNetworkReachabilityManager sharedManager]  setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {      switch (status)        {            case AFNetworkReachabilityStatusUnknown:                callback(1);                break;                            case AFNetworkReachabilityStatusNotReachable:                   callback(2);                break;                            case AFNetworkReachabilityStatusReachableViaWWAN:                   callback(3);                                break;            case AFNetworkReachabilityStatusReachableViaWiFi:                   callback(4);                break;                            default:                                break;        }    }] ;        [[AFNetworkReachabilityManager sharedManager]  startMonitoring];}-(void)postUrl:(NSString *)URLString parameters:(id)parameters call:(void (^)( RespInfo* info))callback{        //首先判斷是否有網路   [self checkNetWorkingIsOrNoUse:^(int StateOrType) {       if (StateOrType==2) {                                   RespInfo* retobj = [[RespInfo alloc]init];             retobj.mBSuccess=NO;             NSString *[email protected]"請檢查網路是否暢通。";             retobj.mMsg=AlertInfo;             callback(retobj);                     }           else       {                                [self POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {               [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 開啟狀態列動畫                                                        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {               NSString *JsonStr=[responseObject JSONString];               NSDictionary *MyDic=[JsonStr objectFromJSONString];               //申明block返回的累               RespInfo* retobj = [[RespInfo alloc]init];               //判斷返回是否成功               NSString *IsOrNoSuccess=[MyDic objectForKey:@"Success"];               if ([IsOrNoSuccess intValue]==1) {                   retobj.mBSuccess=YES;                   //這裡判斷傳回型別,如果為0不去取mObject的值,否則要取                   int JudgeInt=[[MyDic objectForKey:@"ControlType"]intValue];                   if (JudgeInt==0) {//只取列表值                                              NSString *DataListArrayStr=[MyDic objectForKey:@"Rows"];                       retobj.listData=[DataListArrayStr objectFromJSONString];                                          }                   else if(JudgeInt==1)//字取附加字典值                   {                       NSString *addicationDic=[MyDic objectForKey:@"AddicationDictionary"];                       retobj.mObjectDictionary=[addicationDic objectFromJSONString];                   }                   else if(JudgeInt==2)//兩個都取                   {                                              NSString *DataListArrayStr=[MyDic objectForKey:@"Rows"];                       retobj.listData=[DataListArrayStr objectFromJSONString];                                              NSString *addicationDic=[MyDic objectForKey:@"AddicationDictionary"];                       retobj.mObjectDictionary=[addicationDic objectFromJSONString];                   }                   //返回的公用提示訊息                   NSString *AlertInfo=[MyDic objectForKey:@"Msg"];                   retobj.mMsg=AlertInfo;                                  }               else               {                                      retobj.mBSuccess=NO;                                      NSString *AlertInfo=[MyDic objectForKey:@"Msg"];                   retobj.mMsg=AlertInfo;                                  }                              callback(retobj);                                                                       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {                              RespInfo* retobj = [[RespInfo alloc]init];               retobj.mBSuccess=NO;                              retobj.mMsg=error.domain;                          }];                }   }];        }-(void)getUrl:(NSString *)URLString parameters:(id)parameters call:(void (^)(  RespInfo* info))callback{    //首先判斷是否有網路      [self checkNetWorkingIsOrNoUse:^(int StateOrType) {        if (StateOrType==2) {                                    RespInfo* retobj = [[RespInfo alloc]init];            retobj.mBSuccess=NO;            NSString *[email protected]"請檢查網路是否暢通。";            retobj.mMsg=AlertInfo;            callback(retobj);                                }                else        {                                    [self GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; // 開啟狀態列動畫                             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {                                      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];                                                  NSString *JsonStr=[responseObject JSONString];                NSDictionary *MyDic=[JsonStr objectFromJSONString];                //申明block返回的累                RespInfo* retobj = [[RespInfo alloc]init];                //判斷返回是否成功                NSString *IsOrNoSuccess=[MyDic objectForKey:@"Success"];                if ([IsOrNoSuccess intValue]==1) {                    retobj.mBSuccess=YES;                    //這裡判斷傳回型別,如果為0不去取mObject的值,否則要取                    int JudgeInt=[[MyDic objectForKey:@"ControlType"]intValue];                    if (JudgeInt==0) {//只取列表值                                                NSString *DataListArrayStr=[MyDic objectForKey:@"Rows"];                        retobj.listData=[DataListArrayStr objectFromJSONString];                                            }                    else if(JudgeInt==1)//字取附加字典值                    {                        NSString *addicationDic=[MyDic objectForKey:@"AddicationDictionary"];                        retobj.mObjectDictionary=[addicationDic objectFromJSONString];                    }                    else if(JudgeInt==2)//兩個都取                    {                                                NSString *DataListArrayStr=[MyDic objectForKey:@"Rows"];                        retobj.listData=[DataListArrayStr objectFromJSONString];                                                NSString *addicationDic=[MyDic objectForKey:@"AddicationDictionary"];                        retobj.mObjectDictionary=[addicationDic objectFromJSONString];                    }                    //返回的公用提示訊息                    NSString *AlertInfo=[MyDic objectForKey:@"Msg"];                    retobj.mMsg=AlertInfo;                                    }                else                {                                        retobj.mBSuccess=NO;                                        NSString *AlertInfo=[MyDic objectForKey:@"Msg"];                    retobj.mMsg=AlertInfo;                                    }                                callback(retobj);              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {                                RespInfo* retobj = [[RespInfo alloc]init];                retobj.mBSuccess=NO;                                retobj.mMsg=error.domain;                            }];                                }    }];        }// @end

 block返回的類

 

#pragma mark - RespInfo  外層封裝資料@interface RespInfo : AFDataDefine@property (nonatomic,strong) NSArray                 *listData;         //列表資料@property(nonatomic,strong)NSDictionary               *mObjectDictionary;//附帶字典@property (nonatomic,strong) NSString*          mMsg;   //提示訊息@property (nonatomic,assign) BOOL               mBSuccess;    //返回狀態,成功失敗,判斷這個+(RespInfo *)infoWithError:(NSError *)error;+(RespInfo *)infoWithErrorMessage:(NSString *)errMsg;@end

 

調用

 1 #import "ViewController.h" 2 #import "APIClient.h" 3  4 @interface ViewController () 5  6 @end 7  8 @implementation ViewController 9 10 - (void)viewDidLoad {11     [super viewDidLoad];12     // Do any additional setup after loading the view, typically from a nib.13     NSUUID *iD=[[NSUUID alloc]init];14     NSString *UUIDvALUE=[iD UUIDString];15     16     17     18     19     20     NSDictionary *Dic=[[NSDictionary  alloc]initWithObjectsAndKeys:@"0",@"dataType", nil];21     22     [[APIClient sharedClient] getUrl:@"/Mobile/Jmfww.asmx/JmfwwCommunity" parameters:Dic call:^(RespInfo *info) {23         if ([info mBSuccess]) {24             25             26            27             28         }29     }];30     31 }32 33 - (void)didReceiveMemoryWarning {34     [super didReceiveMemoryWarning];35     // Dispose of any resources that can be recreated.36 }37 38 @end

 

AFNetworking 3.1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.