网络中各种代理总结
一共是三个代理方法
NSURLConnectionDataDelegate 既可以用于NSURLConnection的下载代理,也可以用于HTTPS 的代理
NSURLSessionDownloadDelegate NSURLSession的下载代理
NSURLSessionTaskDelegate 既可以用于NSURLSession 大文件的上传代理 也可以用于HTTPS的代理
具体用法
- NSURLConnectionDataDelegate
NSURLConnection下载的正确代理,需要实现下面几个方法
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//在这里初始化流
}
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//在这里接收到数据就写入到沙盒中
}
(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//完成之后,关闭流
}
- NSURLSessionDownloadDelegate NSURLSession下载的代理,需要实现的代理方法有
(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
//下载完成文件之后在这里做处理,一般是把临时文件里面的内容放入到Cache目录下
}
(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
//在这里计算下载进度
}
- NSURLSessionTaskDelegate 实现大文件上传的代理,需要实现的代理方法
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
// 在这里计算上传进度
}
- NSURLSessionTaskDelegate 还可以实现NSURLSession HTTPS的代理,需要实现的代理方法
(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
NSLog(@"%@", challenge.protectionSpace);
// 判断是否是信任服务器证书,HTTPS的访问基本上都是信任证书
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
// 使用受保护空间中的服务器信任创建凭据
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
// 通过 completionHandler 告诉服务器信任证书
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
}
- NSURLConnectionDataDelegate 还可以实现NSURLConnection的HTTPS代理方法
(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"%@", challenge.protectionSpace);
// 判断是否是信任服务器证书
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
// 创建凭据
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
// 发送信任告诉服务器
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
}