NSURLSession笔记

2016-03-24  本文已影响119人  选一个昵称呗

-(void)download
{

// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
// 获得下载任务
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://xxx"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // 文件将来存放的真实路径
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
    // 剪切location的临时文件到真实路径
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];

// 启动任务
[task resume];

}

-(void)post
{

// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx"]];
request.HTTPMethod = @"POST"; // 请求方法
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 请求体
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 启动任务
[task resume];

}

-(void)get2
{

// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://xxx"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 启动任务
[task resume];

}

-(void)get
{

// 获得NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"xxx"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 启动任务
[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]];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx"]]];
// 启动任务
[task resume];

}

NSLog(@"%s", __func__);
// 允许处理服务器的响应,才会继续接收服务器返回的数据
completionHandler(NSURLSessionResponseAllow);

}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{

NSLog(@"%s", __func__);

}

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]];

// 获得下载任务
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://xxx"]];

// 启动任务
[task resume];

}

NSLog(@"didCompleteWithError");

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{

NSLog(@"didResumeAtOffset");

}

-(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);

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{

// 文件将来存放的真实路径
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

// 剪切location的临时文件到真实路径
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;
    // 是否允许使用蜂窝网络(手机自带网络)
    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";

// 设置请求头(告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];

// 设置请求体
NSMutableData *body = [NSMutableData data];

// 文件参数
// 分割线
[body appendData:XMGEncode(@"--")];
[body appendData:XMGEncode(XMGBoundary)];
[body appendData:XMGNewLine];

// 文件参数名
[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];

// 文件数据
[body appendData:XMGNewLine];
[body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
[body appendData:XMGNewLine];

// 结束标记
/*
 --分割线--\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>

     -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
// 如果不是服务器信任类型的证书,直接返回
if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) return;

// void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *)
// NSURLSessionAuthChallengeDisposition : 如何处理这个安全证书
// NSURLCredential :安全证书

// 根据服务器的信任信息创建证书对象
//    NSURLCredential *crdential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

// 利用这个block说明使用这个证书
//    if (completionHandler) {
//        completionHandler(NSURLSessionAuthChallengeUseCredential, crdential);
 //    }

!completionHandler ? : completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential);
  }

@end

上一篇下一篇

猜你喜欢

热点阅读