老的人知道NSURLconnection
年輕的人知道NSURLsession
帥的人在這給大家講解NSURLsession
本文給大家講一個NSURLSession的用法啄骇,并且結(jié)合現(xiàn)在最新版的AFNetworking(3.1.0)來實現(xiàn)同樣的功能奋刽,將會帶來全新的體驗哦:
- NSURLSession的基本講解
- 實現(xiàn)GET,POST,下載圖片等功能
- 用最新版的AFN(3.1.0)來實現(xiàn)同樣的功能
NSURLSession的基本講解
在開發(fā)網(wǎng)絡(luò)相關(guān)的應(yīng)用红竭,就必然需要使用到HTTP請求來發(fā)送或者接收數(shù)據(jù)潦刃。最主要的就是使用GET方法或者POST方法。本文將詳細介紹NSURLSession在HTTP請求在iOS開發(fā)中的編程實現(xiàn)
首先要明白NSURLSession有那幾部分組成
在以NSURLSession為主流的網(wǎng)絡(luò)請求的時候右遭,就要先弄清楚他們的關(guān)系做盅,
由上圖可看出缤削,整個NSURLSession就想一個帝王,如秦始皇一樣叼的帝王吹榴。暫且我們把NSURLSession當一個秦王亭敢,手下就要有治理軍隊的大將軍和梳理政務(wù)的丞相兩大馬車。這里的NSURLSessionConfiguration就好比是一個上將軍图筹。上將軍手底下有多個大軍的前將軍這里就好比就是無數(shù)個NSURLSessionTask帅刀,這里就是手底下的各種兵種了。
NSURLSessionTask:就是數(shù)據(jù)操作的小兵:
NSURLSessionDataTask:普通的數(shù)據(jù)傳輸远剩,拿到的數(shù)據(jù)是NSData格式扣溺,你可以根據(jù)數(shù)據(jù)原本的格式進行相應(yīng)的轉(zhuǎn)換。
NSURLSessionUploadTask:用于上傳
NSURLSessionDownloadTask:用于下載瓜晤,這個類與其它兩個類有點不一樣锥余,這個類下載到的東西是直接寫在一個臨時文件中的,下載好之后它會給你一個臨時文件的指針痢掠,然后自己手動保存驱犹。
廢話不多看 對比代碼的實現(xiàn)
使用 GET 請求
/**
* 基本的網(wǎng)絡(luò)請求
*/
-(void)basicURLRequest {
NSString *url = @"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&forum_id=1&type=1&count=10&page=1&delcache=0";
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
// 基本網(wǎng)絡(luò)請求
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSStringEncodingConversionAllowLossy];
NSLog(@"%@",string);
}
}
}];
[dataTask resume];
}
// ————————————————看一下AFN的網(wǎng)絡(luò)請求
/**
* 基于AFN的網(wǎng)絡(luò)POST請求
*/
-(void)AFNBasicRequesthttpBody {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSString *url = @"http://open.qyer.com/qyer/bbs/forum_thread_list";
NSDictionary * dict = @{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"forum_id":@"1"};
// 這里把字典轉(zhuǎn)換成GET請求后的憑接地址
NSString *URLFellowString = [@"?" stringByAppendingString:[NSString queryStringFromDictionary:dict addingPercentEscapes:YES]];
NSURL *URL = [NSURL URLWithString:[url stringByAppendingString:URLFellowString]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"-------Error: %@", error);
} else {
NSLog(@">>>>>%@", responseObject);
}
}];
[dataTask resume];
}
使用 GET 請求
/**
* 基本的POST請求
*/
-(void)BasicPostRequst {
//1.創(chuàng)建會話對象
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
//2.根據(jù)會話對象創(chuàng)建task
NSURL *url = [NSURL URLWithString:@"http://icloud.chinacloudapp.cn/icloud/app/v1/user/userlogin.do"];
//3.創(chuàng)建可變的請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設(shè)置向服務(wù)器發(fā)送json格式數(shù)據(jù)
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//4.修改請求方法為POST
request.HTTPMethod = @"POST";
NSDictionary *parameters = @{@"phone":@"18790723015",@"pwd":@"123456",@"device_token":@"71c26d22d85686e37658524adc1541ce88bc05c4f0e788b0ffe315e9e3f98378",@"client_type":@1};
NSError* error;
//5.設(shè)置請求體
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
request.HTTPBody = jsonData;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//8.解析數(shù)據(jù)
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",dict);
}];
//7.執(zhí)行任務(wù)
[dataTask resume];
}
// ___________下面基于AFN的網(wǎng)絡(luò)POST請求
/**
* 基于AFN的網(wǎng)絡(luò)POST請求
*/
-(void)AFNHttpPostRequest {
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *url = [NSURL URLWithString:@"http://icloud.chinacloudapp.cn/icloud/app/v1/user/userlogin.do"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSDictionary *parameters = @{@"phone":@"15010206793",@"pwd":@"123456",@"device_token":@"71c26d22d85686e37658524adc1541ce88bc05c4f0e788b0ffe315e9e3f98378",@"client_type":@1};
NSError* error;
//5.設(shè)置請求體
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
request.HTTPBody = jsonData;
NSURLSessionDataTask * task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"---%@",responseObject);
}
}];
[task resume];
}
圖片下載
/**
* 基本下載圖片方法
*/
-(void)BaseDownloadImage {
NSURL * url = [NSURL URLWithString:@"http://image.tianjimedia.com/uploadImages/2011/252/8GO666XNQM49.jpg"];
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
// 當statusCode等于200時,表示網(wǎng)絡(luò)沒問題
NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
UIImage *imageData = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = imageData;
});
}
}];
[task resume];
}
//______________基于AFN的圖片下載
/**
* 基于AFN的網(wǎng)絡(luò)下載
*/
-(void)AFNDownloadImage {
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
NSURL * url = [NSURL URLWithString:@"http://image.tianjimedia.com/uploadImages/2011/252/8GO666XNQM49.jpg"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (!error) {
//此處已經(jīng)在主線程了
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
self.imageView.image = image;
}
}];
[task resume];
}
注釋
如有問題可添加我的QQ:1290925041
還可添加QQ群:234812704(洲洲哥學院)
歡迎各位一塊學習足画,提高逼格雄驹!
也可以添加洲洲哥的微信公眾號
新的網(wǎng)絡(luò)用法要使用,不要去使用AFN2.0.x的版本了淹辞。小伙看這里 你會發(fā)現(xiàn)很多哦
關(guān)注洲洲個的公眾號医舆,提高裝逼技能就靠他了