-(void)download
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://xxx"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件將來存放的真實(shí)路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實(shí)路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 啟動任務(wù)
[task resume];
}
-(void)post
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx"]];
request.HTTPMethod = @"POST"; // 請求方法
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 請求體
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
-(void)get2
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://xxx"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
-(void)get
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"xxx"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務(wù)
[task resume];
}
NSURLSessionDataDelegate
@interface ViewController () <NSURLSessionDataDelegate>
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 創(chuàng)建任務(wù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx"]]];
// 啟動任務(wù)
[task resume];
}
- pragma mark - <NSURLSessionDataDelegate>
1.接收到服務(wù)器的響應(yīng)
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s", __func__);
// 允許處理服務(wù)器的響應(yīng)余赢,才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
- 2.接收到服務(wù)器的數(shù)據(jù)(可能會被調(diào)用多次)
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"%s", __func__);
}
- 3.請求成功或者失斦┢谩(如果失敗,error有值)
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
@end
NSURLSessionDownloadDelegate
@interface ViewController () <NSURLSessionDownloadDelegate>
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self download];
}
-(void)download
{
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://xxx"]];
// 啟動任務(wù)
[task resume];
}
- pragma mark - <NSURLSessionDownloadDelegate>
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset");
}
- 每當(dāng)寫入數(shù)據(jù)到臨時文件時,就會調(diào)用一次這個方法
- totalBytesExpectedToWrite:總大小
- totalBytesWritten: 已經(jīng)寫入的大小
- bytesWritten: 這次寫入多少
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
- 下載完畢就會調(diào)用一次這個方法
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// 文件將來存放的真實(shí)路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實(shí)路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
@end
NSURLSession上傳文件
#define XMGBoundary @"xxx"
#define XMGEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define XMGNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
#import "ViewController.h"
@interface ViewController ()
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
-(NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
cfg.timeoutIntervalForRequest = 10;
// 是否允許使用蜂窩網(wǎng)絡(luò)(手機(jī)自帶網(wǎng)絡(luò))
cfg.allowsCellularAccess = YES;
_session = [NSURLSession sessionWithConfiguration:cfg];
}
return _session;
}
-(void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx"]];
request.HTTPMethod = @"POST";
// 設(shè)置請求頭(告訴服務(wù)器,這是一個文件上傳的請求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
// 設(shè)置請求體
NSMutableData *body = [NSMutableData data];
// 文件參數(shù)
// 分割線
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];
// 文件參數(shù)名
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:XMGNewLine];
// 文件的類型
[body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:XMGNewLine];
// 文件數(shù)據(jù)
[body appendData:XMGNewLine];
[body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];
// 結(jié)束標(biāo)記
/*
--分割線--\r\n
*/
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGEncode(@"--")];
[body appendData:XMGNewLine];
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
}
@end
NSURLSession https處理
#import "ViewController.h"
@interface ViewController () <NSURLSessionTaskDelegate>
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com/"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[task resume];
}
#pragma mark - <NSURLSessionTaskDelegate>
- challenge : 挑戰(zhàn)琳拭、質(zhì)詢
- completionHandler : 通過調(diào)用這個block账锹,來告訴URLSession要不要接收這個證書
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
// 如果不是服務(wù)器信任類型的證書,直接返回
if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) return;
// void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *)
// NSURLSessionAuthChallengeDisposition : 如何處理這個安全證書
// NSURLCredential :安全證書
// 根據(jù)服務(wù)器的信任信息創(chuàng)建證書對象
// NSURLCredential *crdential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
// 利用這個block說明使用這個證書
// if (completionHandler) {
// completionHandler(NSURLSessionAuthChallengeUseCredential, crdential);
// }
!completionHandler ? : completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential);
}
@end