网络请求AFNetworking使用量不用过多的说了,但是在开发过程中,需要用到自己去封装一个网络请求,此处主要是说一下NSUrlSession的用法,顺便说一下,这个网络请求库,是同时支持HTTP和HTTPS请求的,应为在iOS9之后,默认的请求方式是HTTPS;
当然,Xcode工程中需要在info.plist文件中加入下面的节点:App Transport Security Settings(字典类型) ->添加Allow Arbitrary Loads为bool类型,设置为YES,大概意思就是说,是否允许任性的加载? 设为 YES 的话就将禁用了 AppTransportSecurity 转而使用用户自定义的设置。
首先创建一个继承与NSObject的.h和.m的类,.h中的代码如下:
#import <Foundation/Foundation.h>
typedef void (^CompletioBlock)(NSDictionary *dic, NSURLResponse *response, NSError *error);
typedef void (^SuccessBlock)(NSDictionary *data);
typedef void (^FailureBlock)(NSError *error);
@interface SYNetworkHelper : NSObject<NSURLSessionDelegate>
/**
* get请求
*/
+ (void)getWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;
/**
* post请求
*/
+ (void)postWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;
@end
.m中的实现如下:
#import "SYNetworkHelper.h"
//定义一个变量
static SYFlashNetworkHelper *helper = nil;
@implementation SYNetworkHelper
//实例化对象
+ (instancetype)shareHelper
{
@synchronized(self) {
if (!helper) {
helper = [[SYFlashNetworkHelper alloc] init];
}
return helper;
}
}
//get请求
+ (void)getWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock
{
[self shareHelper];
NSMutableString *mutableUrl = [[NSMutableString alloc] initWithString:url];
if ([parameters allKeys]) {
[mutableUrl appendString:@"?"];
for (id key in parameters) {
NSString *value = [[parameters objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&", key, value]];
}
}
NSString *urlEnCode = [[mutableUrl substringToIndex:mutableUrl.length - 1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:helper delegateQueue:queue];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
failureBlock(error);
} else {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
successBlock(dic);
}
}];
[dataTask resume];
}
//post请求
+ (void)postWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock
{
[self shareHelper];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];
//设置请求方式
request.HTTPMethod = @"POST";
NSString *postStr = [SYFlashNetworkHelper parseParams:parameters];
//设置请求体
request.HTTPBody = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:helper delegateQueue:queue];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
failureBlock(error);
} else {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
successBlock(dic);
}
}];
[dataTask resume];
}
//把NSDictionary解析成post格式的NSString字符串
+ (NSString *)parseParams:(NSDictionary *)params
{
NSString *keyValueFormat;
NSMutableString *result = [NSMutableString new];
NSMutableArray *array = [NSMutableArray new];
//实例化一个key枚举器用来存放dictionary的key
NSEnumerator *keyEnum = [params keyEnumerator];
id key;
while (key = [keyEnum nextObject]) {
keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];
[result appendString:keyValueFormat];
[array addObject:keyValueFormat];
}
return result;
}
#pragma mark - NSURLSessionDelegate 代理方法
//主要就是处理HTTPS请求的
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = protectionSpace.serverTrust;
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);
} else {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
}
@end