一吏饿、學(xué)習(xí)蘋果提供的原生網(wǎng)絡(luò)請(qǐng)求方法
在iOS項(xiàng)目開發(fā)中春寿,網(wǎng)絡(luò)請(qǐng)求是必不可少的部分步脓,大多數(shù)iOS開發(fā)者會(huì)使用第三方的網(wǎng)絡(luò)請(qǐng)求框架AFNetworking堡僻。AFNetworking基本每個(gè)iOS開發(fā)者都知道,但是卻很少有人去閱讀過它的源碼实撒。都會(huì)用姊途,但卻不知道它的原理,可謂是最熟悉的陌生人知态。要想弄懂AFNetworking的原理捷兰,首先要掌握蘋果提供的原生網(wǎng)絡(luò)請(qǐng)求方法,AFNetworking也是在這個(gè)基礎(chǔ)之上進(jìn)行二次封裝的负敏。本篇文章主要是介紹原生的網(wǎng)絡(luò)請(qǐng)求方法贡茅,內(nèi)容很簡(jiǎn)單。
NSURLSessionDataTask 是 NSURLSessionTask 的子類其做,是一個(gè)具體的網(wǎng)絡(luò)請(qǐng)求類顶考,是網(wǎng)絡(luò)請(qǐng)求中最常用的請(qǐng)求之一。NSURLSessionDataTask 用來請(qǐng)求數(shù)據(jù)妖泄,可以用來下載數(shù)據(jù)資源驹沿,例如 JSON 數(shù)據(jù),圖片數(shù)據(jù)等蹈胡。
1渊季、NSURLSession 的實(shí)例方法一
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
該方法中會(huì)自動(dòng)將 url 轉(zhuǎn)換為一個(gè)請(qǐng)求對(duì)象(NSURLRequest),并且該請(qǐng)求對(duì)象是 GET 請(qǐng)求方式罚渐∪春海回調(diào)方法是在子線程中運(yùn)行的,所以如果在回調(diào)方法中刷新 UI 必須回到主線程中荷并。使用該方法的缺點(diǎn)是不能監(jiān)聽獲取數(shù)據(jù)的進(jìn)度病涨,因?yàn)橹挥挟?dāng)全部請(qǐng)求完數(shù)據(jù)后,才會(huì)調(diào)用這個(gè)方法璧坟,也就是說既穆,data 中的數(shù)據(jù)是請(qǐng)求的全部數(shù)據(jù)。
代碼示例
@property (nonatomic, strong) NSURLSessionDataTask * dataTask;
self.urlString = @"https://icweiliimg9.pstatp.com/weili/l/462548014891532564.jpg";
- (void)GETButtonClick
{
self.dataTask = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:self.urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
self.imgView.image = [UIImage imageWithData:data];
});
}];
[self.dataTask resume];
}
2雀鹃、NSURLSession 的實(shí)例方法二
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
方法一只能是GET請(qǐng)求方式幻工,方法二可以手動(dòng)設(shè)置請(qǐng)求方式GET或POST。
代碼示例
- (void)PostButtonClick
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlString]];
request.HTTPMethod = @"POST";
self.dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
self.imgView.image = [UIImage imageWithData:data];
});
}];
[self.dataTask resume];
}
3黎茎、NSURLSession 的代理方法
方法一和方法二唯一的缺點(diǎn)就是不能監(jiān)控請(qǐng)求進(jìn)度囊颅,因?yàn)橹挥挟?dāng)請(qǐng)求完全部的數(shù)據(jù)后才會(huì)調(diào)用回調(diào)方法,如果想要監(jiān)控請(qǐng)求進(jìn)度傅瞻,必須使用代理的方法踢代。
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue;
代碼示例
- (void)request
{
self.urlString = @"https://icweiliimg9.pstatp.com/weili/l/462548014891532564.jpg";
self.data = [[NSMutableData alloc] init];
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
self.dataTask = [self.session dataTaskWithURL:[NSURL URLWithString:self.urlString]];
[self.dataTask resume];
}
#pragma mark 接受到數(shù)據(jù)時(shí)調(diào)用,可能會(huì)調(diào)用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
[self.data appendData:data];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"progress:%f",(float)self.dataTask.countOfBytesReceived);
});
}
#pragma mark 請(qǐng)求結(jié)束或失敗時(shí)調(diào)用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
self.imgView.image = [UIImage imageWithData:self.data];
});
}
二嗅骄、基于原生網(wǎng)絡(luò)請(qǐng)求方法進(jìn)行封裝
掌握了原生的網(wǎng)絡(luò)請(qǐng)求方法胳挎,我們便可以自己封裝一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求類,在簡(jiǎn)單的項(xiàng)目中可以替代AFNetworking溺森,或者可以在自己的SDK中進(jìn)行使用慕爬。下面就直接上代碼了,只是對(duì)文章前面的內(nèi)容進(jìn)行了封裝屏积。
1医窿、HSNetworkTool.h 頭文件
@interface HSNetworkTool : NSObject
+ (instancetype)shareInstance;
//請(qǐng)求URL
@property (nonatomic, copy) NSString *requestURL;
typedef void(^HSResponseSuccessBlock)(NSDictionary *responseObject);
typedef void(^HSResponseFailBlock)(NSError *error);
/**
* @brief GET請(qǐng)求方法
* @author yuancan
* @param relativePath 接口名稱
* @param params 請(qǐng)求參數(shù)
* @param successBlock 請(qǐng)求成功回調(diào)
* @param failBlock 請(qǐng)求失敗回調(diào)
*/
- (void)requestGET:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock;
/**
* @brief POST請(qǐng)求方法
* @author yuancan
* @param relativePath 接口名稱
* @param params 請(qǐng)求參數(shù)
* @param successBlock 請(qǐng)求成功回調(diào)
* @param failBlock 請(qǐng)求失敗回調(diào)
*/
- (void)requestPOST:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock;
/**
* @brief JSON格式網(wǎng)絡(luò)接口請(qǐng)求方法
* @author yuancan
*
* @param relativePath 接口名稱
* @param params 請(qǐng)求參數(shù)
* @param successBlock 請(qǐng)求成功回調(diào)
* @param failBlock 請(qǐng)求失敗回調(diào)
*/
- (void)requestJsonPost:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock;
@end
2、HSNetworkTool.m 源文件
#import "HSNetworkTool.h"
@implementation HSNetworkTool
+ (instancetype)shareInstance
{
static HSNetworkTool *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[HSNetworkTool alloc] init];
[_sharedInstance configure];
});
return _sharedInstance;
}
- (void)configure
{
self.requestURL = @"https://wx.ahdms.top";
}
- (void)requestHTTPMethod:(NSString *)httpMenthod relativePath:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock
{
NSMutableString *paramsString = [[NSMutableString alloc] initWithCapacity:0];
for (int i=0;i<[params allKeys].count;i++) {
NSString *key = [[params allKeys] objectAtIndex:i];
[paramsString appendString:[NSString stringWithFormat:@"%@=%@",key,[params objectForKey:key]]];
if (i < [params allKeys].count-1) {
[paramsString appendString:@"&"];
}
}
NSString *urlString = [NSString stringWithFormat:@"%@%@", self.requestURL, relativePath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
request.HTTPMethod = httpMenthod;
request.HTTPBody = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
if (successBlock) {
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
successBlock(responseObject);
}
} else {
if (failBlock) {
failBlock(error);
}
}
}];
[dataTask resume];
}
- (void)requestGET:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock
{
[self requestHTTPMethod:@"GET" relativePath:relativePath params:params successBlock:^(NSDictionary * _Nonnull responseObject) {
if (successBlock) {
return successBlock(responseObject);
}
} failBlock:^(NSError * _Nonnull error) {
if (failBlock) {
return failBlock(error);
}
}];
}
- (void)requestPOST:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock
{
[self requestHTTPMethod:@"POST" relativePath:relativePath params:params successBlock:^(NSDictionary * _Nonnull responseObject) {
if (successBlock) {
return successBlock(responseObject);
}
} failBlock:^(NSError * _Nonnull error) {
if (failBlock) {
return failBlock(error);
}
}];
}
- (void)requestJsonPost:(NSString *)relativePath params:(NSDictionary *)params successBlock:(HSResponseSuccessBlock)successBlock failBlock:(HSResponseFailBlock)failBlock
{
NSString *urlString = [NSString stringWithFormat:@"%@%@", self.requestURL, relativePath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
request.HTTPMethod = @"POST";
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
if (successBlock) {
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
successBlock(responseObject);
}
} else {
if (failBlock) {
failBlock(error);
}
}
}];
[dataTask resume];
}
@end
3炊林、使用示例
GET請(qǐng)求
[[HSNetworkTool shareInstance] requestGET:@"/login"
params:nil
successBlock:^(NSDictionary * _Nonnull responseObject) {
}
failBlock:^(NSError * _Nonnull error) {
}];
POST請(qǐng)求
[[HSNetworkTool shareInstance] requestPOST:@"/login"
params:nil
successBlock:^(NSDictionary * _Nonnull responseObject) {
}
failBlock:^(NSError * _Nonnull error) {
}];
JSON格式的POST請(qǐng)求
[[HSNetworkTool shareInstance] requestJsonPost:@"/login"
params:nil
successBlock:^(NSDictionary * _Nonnull responseObject) {
}
failBlock:^(NSError * _Nonnull error) {
}];
轉(zhuǎn)載https://blog.csdn.net/u010545480/article/details/100538799