NSURLSession

NSURLSession


  • 相比NSURLConnection,NSURLSession提供了配置会话缓存、协议、cookie和证书能力
  • 通过三个子类来完成文件上传、文件下载和获取数据
    • NSURLSessionData、NSURLSessionUploadTask、NSURLSessionDownloadTask,默认任务运行在其他非主线程中

数据请求

#pragma mark 请求数据
-(void)loadJsonData{
	//1.创建url
	NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.208/ViewStatus.aspx?userName=%@&password=%@",@"KenshinCui",@"123"];
	urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *url=[NSURL URLWithString:urlStr];
	//2.创建请求
	NSURLRequest *request=[NSURLRequest requestWithURL:url];

	//3.创建会话(这里使用了一个全局会话,也可以自己创建一个会话)并且启动任务
	NSURLSession *session=[NSURLSession sharedSession];
	//从会话创建任务
	NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    	if (!error) {
       	 NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        	NSLog(@"%@",dataStr);
    	}else{
       	 NSLog(@"error is :%@",error.localizedDescription);
    	}
	}];

	[dataTask resume];//恢复线程,启动任务
}

文件上传

#pragma mark 取得mime types
-(NSString *)getMIMETypes:(NSString *)fileName{
		return @"image/jpg";
}

#pragma mark 取得数据体
-(NSData *)getHttpBody:(NSString *)fileName{
NSString *boundary=@"KenshinCui";
NSMutableData *dataM=[NSMutableData data];
NSString *strTop=[NSString stringWithFormat:@"--%@
Content-Disposition: form-data; name="file1"; filename="%@"
Content-Type: %@

",boundary,fileName,[self getMIMETypes:fileName]];
NSString *strBottom=[NSString stringWithFormat:@"
--%@--",boundary];
NSString *filePath=[[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSData *fileData=[NSData dataWithContentsOfFile:filePath];
[dataM appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]];
[dataM appendData:fileData];
[dataM appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]];
return dataM;
}

#pragma mark 上传文件
-(void)uploadFile{
NSString *fileName=@"pic.jpg";
//1.创建url
NSString *urlStr=@"http://192.168.1.208/FileUpload.aspx";
urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];
//2.创建请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod=@"POST";

//3.构建数据
NSString *path=[[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSData *data=[self getHttpBody:fileName];
request.HTTPBody=data;

[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",@"KenshinCui"] forHTTPHeaderField:@"Content-Type"];



//4.创建会话
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask=[session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
        NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",dataStr);
    }else{
        NSLog(@"error is :%@",error.localizedDescription);
    }
}];

[uploadTask resume];
}	

文件下载

-(void)downloadFile{
//1.创建url
NSString *fileName=@"1.jpg";
NSString *urlStr=[NSString stringWithFormat: @"http://192.168.1.208/FileDownload.aspx?file=%@",fileName];
urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];
//2.创建请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

//3.创建会话(这里使用了一个全局会话)并且启动任务
NSURLSession *session=[NSURLSession sharedSession];

NSURLSessionDownloadTask *downloadTask=[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    if (!error) {
        //注意location是下载后的临时保存路径,需要将它移动到需要保存的位置
        
        NSError *saveError;
        NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *savePath=[cachePath stringByAppendingPathComponent:fileName];
        NSLog(@"%@",savePath);
        NSURL *saveUrl=[NSURL fileURLWithPath:savePath];
        [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
        if (!saveError) {
            NSLog(@"save sucess.");
        }else{
            NSLog(@"error is :%@",saveError.localizedDescription);
        }
        
    }else{
        NSLog(@"error is :%@",error.localizedDescription);
    }
}];

[downloadTask resume];
}	

会话

NSURLSession支持进程三种会话:

  • defaultSessionConfiguration:进程内会话(默认会话),用硬盘来缓存数据。
  • ephemeralSessionConfiguration:临时的进程内会话(内存),不会将cookie、缓存储存到本地,只会放到内存中,当应用程序退出后数据也会消失。
  • backgroundSessionConfiguration:后台会话,相比默认会话,该会话会在后台开启一个线程进行网络数据处理。
    • 程序的后台下载和上传,苹果官方将其称为进程之外的上传和下载,这些任务都是交给后台守护线程完成的,而非应用程序本身。

    • 当NSURLSession在后台开启几个任务之后,如果有其中几个任务完成后系统会调用此应用程序的

        -(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
        
        代理方法;此方法会包含一个competionHandler(此操作表示应用完成所有处理工作),通常我们会保存此对象;直到最后一个任务完成,此时会重新通过会话标识(上面sessionConfig中设置的)找到对应的会话并调用
        
        NSURLSession的
        
        -(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
        
        代理方法,在这个方法中通常可以进行UI更新,并调用completionHandler通知系统已经完成所有操作。:
原文地址:https://www.cnblogs.com/sunyanyan/p/5124263.html