Ios NSURLSession 及AFNetworking初步使用

网络方面,我们一般使用系统自带的NSURLSession和第三方AFNetworking,下面大致总结一下其基本用法.

NSURLSession

NSURLSessionDataTask 发送 GET 请求

    //确定请求路径
    NSURL *url = [NSURL URLWithString: @"http://api.meituan.com/group/v1/deal/topic/discount/city/1?ci=1&client=iphone&movieBundleVersion=100&msid=48E2B810-805D-4821-9CDD-D5C9E01BC98A2015-06-17-14-50363&userid=10086&utm_campaign=AgroupBgroupD100Fab_chunceshishuju__a__a___b1junglehomepagecatesort__b__leftflow___ab_gxhceshi__nostrategy__leftflow___ab_gxhceshi0202__b__a___ab_pindaochangsha__a__leftflow___ab_xinkeceshi__b__leftflow___ab_gxtest__gd__leftflow___ab_gxh_82__nostrategy__leftflow___ab_pindaoshenyang__a__leftflow___i_group_5_2_deallist_poitype__d__d___ab_b_food_57_purepoilist_extinfo__a__a___ab_trip_yidizhoubianyou__b__leftflow___ab_i_group_5_3_poidetaildeallist__a__b___ab_waimaizhanshi__b__b1___a20141120nanning__m1__leftflow___ab_pindaoquxincelue__a__leftflow___ab_i_group_5_5_onsite__b__b___ab_i_group_5_6_searchkuang__a__leftflow&utm_content=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&utm_medium=iphone&utm_source=AppStore&utm_term=5.7&uuid=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&version_name=5.7"
];
    //创建 NSURLSession 对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    /**
     根据对象创建 Task 请求
     
     url  方法内部会自动将 URL 包装成一个请求对象(默认是 GET 请求)
     completionHandler  完成之后的回调(成功或失败)
     
     param data     返回的数据(响应体)
     param response 响应头
     param error    错误信息
     */
    
    NSURLSessionTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析服务器返回的数据
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
  
    //发送请求(执行Task)
    [dataTask resume];
    
 

NSURLSessionDataTask 发送 Post 请求


    //确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //创建可变请求对象
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    //修改请求方法
    requestM.HTTPMethod = @"POST";
    //设置请求体
    requestM.HTTPBody = [@"username=520&pwd=520&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    //创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //创建请求 Task
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //解析返回的数据
    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    //发送请求
    [dataTask resume];
    

AFNetworking

AFHTTPSessionManager 发送Get请求

 AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
 [session GET:URLString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
       NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"网络请求失败"); 
        
    }];

AFNetworking网络监听

#import "AppDelegate.h"

#import 



@interface AppDelegate ()

@property(nonatomic,strong)AFNetworkReachabilityManager *reachabilityManager;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //创建网络监控对象
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];

    //设置监听
    [_reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未识别的网络");
                break;

            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"不可达的网络(未连接)");
                break;

            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"2G,3G,4G...的网络");
                break;

            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"wifi的网络");
                break;
            default:
                break;
        }
    }];

    //开始监听网络状况.
    [_reachabilityManager startMonitoring];
    return YES;
}


-(void)dealloc{

    //停止监听网络状况.
    [_reachabilityManager stopMonitoring];

}

参考文献

开发只懂 AFN ?搞定 NSURLSession 才是硬道理
华山论剑之浅谈iOS网络请求终结者/网络状况监控终结者--AFNetworking

你可能感兴趣的:(Ios NSURLSession 及AFNetworking初步使用)