在iOS開發(fā)中, 有很多十分好用的庫, 以至于大家達成了共識, 每次在遇到這個功能自然而然的就想到用哪個第三方庫. 這是很好的, 畢竟是各種大牛的長時間維護的勞動成果. 但是作為開發(fā)者, 只會用別人的第三方庫, 就對自身的技術(shù)成長有很大的障礙. 我們需要知道他們是怎么實現(xiàn)的, 大家可以抽空看看平時經(jīng)常用的各種第三方庫的源碼, 相信你最后會技術(shù)大漲!
在這里, 我們是要介紹一下關(guān)于網(wǎng)絡請求, 大家都知道AFNetworking, 這是當然的, 因為這是一個相當成熟的庫, 幾乎絕大多數(shù)iOSapp都在用它. 但是我們這里想介紹一下如何利用NSURLSession, 自己寫一個請求類, 可以不依賴于其他第三方庫.
LCNetworking.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
typedef void (^SuccessBlock)(id responseObject);
typedef void (^FailureBlock)(NSString *error);
@interface LCNetworking : NSObject
//原生GET網(wǎng)絡請求
+ (void)getWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure;
+ (void)PostWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure;
@end
LCNetworking.m
#import "LCNetworking.h"
NSString *const ResponseErrorKey = @"com.alamofire.serialization.response.error.response";
NSInteger const Interval = 30;
@interface LCNetworking ()
@end
@implementation LCNetworking
//原生GET網(wǎng)絡請求
+ (void)getWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure
{
//完整URL
NSString *urlString = [NSString string];
if (params) {
//參數(shù)拼接url
NSString *paramStr = [self dealWithParam:params];
urlString = [url stringByAppendingString:paramStr];
}else{
urlString = url;
}
//對URL中的中文進行轉(zhuǎn)碼
NSString *pathStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:pathStr]];
request.timeoutInterval = Interval;
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
//利用iOS自帶原生JSON解析data數(shù)據(jù) 保存為Dictionary
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
success(dict);
}else{
NSHTTPURLResponse *httpResponse = error.userInfo[ResponseErrorKey];
if (httpResponse.statusCode != 0) {
NSString *ResponseStr = [self showErrorInfoWithStatusCode:httpResponse.statusCode];
failure(ResponseStr);
} else {
NSString *ErrorCode = [self showErrorInfoWithStatusCode:error.code];
failure(ErrorCode);
}
}
});
[task resume];
}
//原生POST請求
+ (void)PostWithURL:(NSString *)url Params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
//把字典中的參數(shù)進行拼接
NSString *body = [self dealWithParam:params];
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
//設置請求體
[request setHTTPBody:bodyData];
//設置本次請求的數(shù)據(jù)請求格式
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// 設置本次請求請求體的長度(因為服務器會根據(jù)你這個設定的長度去解析你的請求體中的參數(shù)內(nèi)容)
[request setValue:[NSString stringWithFormat:@"%ld", bodyData.length] forHTTPHeaderField:@"Content-Length"];
//設置請求最長時間
request.timeoutInterval = Interval;
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
//利用iOS自帶原生JSON解析data數(shù)據(jù) 保存為Dictionary
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
success(dict);
}else{
NSHTTPURLResponse *httpResponse = error.userInfo[ResponseErrorKey];
if (httpResponse.statusCode != 0) {
NSString *ResponseStr = [self showErrorInfoWithStatusCode:httpResponse.statusCode];
failure(ResponseStr);
} else {
NSString *ErrorCode = [self showErrorInfoWithStatusCode:error.code];
failure(ErrorCode);
}
}
}];
[task resume];
}
使用方法:
直接把這兩個類拖到要使用的項目中, 導入頭文件, 然后調(diào)取.h文件里面留的接口就可以, 這些東西就不詳細的說了.
這里是使用demo的地址, 不會的可以參照demo使用:
https://github.com/LeoTnT/LCNetWorking
注意: 這個網(wǎng)絡請求類只是實現(xiàn)了GET, POST的請求, 沒有具體配置, 如果要使用還要參照具體情況再改代碼, 謝謝~