iOS--网络编程

一、将请求回来的信息加载到UI

二、网络下载文件

1、小文件下载使用block方式,不能监听下载进度

1)准备request

NSString *path = [NSString stringWithFormat:@"http://127.0.0.1/设计模式解析.pdf"];

path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:path];

NSMutableURLRequest *reuqest = [NSMutableURLRequest requestWithURL:url];

2) 准备发送请求的NSURLSession对象

NSURLSession *session = [NSURLSession sharedSession];

3)发送请求并获得NSURLSessionDownloadTask对象,采用block方式

NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:reuqest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

NSString *documentPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

NSFileManager *fileMange = [NSFileManager defaultManager];

NSData *data = [NSData dataWithContentsOfFile:[location path]];

[fileMange createFileAtPath:documentPath contents:data attributes:nil];

NSLog(@"%@",documentPath);

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

NSLog(@"%@",httpResponse.allHeaderFields);

}];

4)开始请求

[downloadTask resume];

2、大文件采用代理方式,能够监听下载进度

1)准备request

NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/git.mov"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

2)获取到发送请求的NSURLSession对象,并设置会话模式、代理(记得遵守下载的协议)、线程队列

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];

PS:三种会话方式

进程内会话(默认会话),用硬盘来缓存数据。

defaultSessionConfiguration

临时的进程内会话(内存),不会将cookie、缓存储存到本地,只会放到内存中,当应用程序退出后数据也会消失

ephemeralSessionConfiguration

后台会话,相比默认会话,该会话会在后台开启一个线程进行网络数据处理

backgroundSessionConfiguration

3)获取到NSURLSessionDownloadTask对象,不需要用block

NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];

4) 实现代理方法

//下载完成时调用

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

NSLog(@"finished=%@",NSHomeDirectory());

}

//下载过程中调用

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

//参数分别是

当前这次下载的数据

已经下载的总数据

期待下载的总数据

NSLog(@"%lld %lld %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);

NSLog(@"%@",[NSThread currentThread]);

}

5)下载控制

//开始(恢复)下载

[downloadTask resume];

//挂起下载

[downloadTask suspend];

//取消下载

[downloadTask cancel];

你可能感兴趣的:(iOS--网络编程)