NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS,所以也可以使用。NSURLConnection上传图片,可以自己找资料。
NSURLConnection相对于NSURLSession,安全性低。NSURLConnection下载有峰值,比较麻烦处理。
尽管适配最低版本iOS7,也可以使用NSURLSession。AFN已经不支持NSURLConnection。
NSURLSession:会话。默认是挂起状态,如果要请求网络,需要开启。
[NSURLSession sharedSession] 获取全局的NSURLSession对象。在iPhone的所有app共用一个全局session.
NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask
NSURLSessionDownloadTask -> NSURLSessionTask
NSURLSessionDownloadTask下载,默认下载到tmp文件夹。下载完成后删除临时文件。所以我们要在删除文件之前,将它移动到Cache里。
//创建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//创建请求
// NSURLRequest * request = [NSURLRequest requestWithURL:url];
//创建Session
NSURLSession * session = [NSURLSession sharedSession];
//创建任务
NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//开启网络任务
[task resume];
//创建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//创建请求
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//创建Session
NSURLSession * session = [NSURLSession sharedSession];
//创建任务
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//开启网络任务
[task resume];
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//设置请求方法
request.HTTPMethod = @"POST";
//设置请求体
request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}] resume];
NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//location 下载到沙盒的地址
NSLog(@"下载完成%@",location);
//response.suggestedFilename 响应信息中的资源文件名
NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"缓存地址%@",cachesPath);
//获取文件管理器
NSFileManager * mgr = [NSFileManager defaultManager];
//将临时文件移动到缓存目录下
//[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型
//URL如果地址不正确,生成的url对象为空
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
}];
[downloadTask resume];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
//允许接受服务器回传数据
completionHandler(NSURLSessionResponseAllow);
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
bytesWritten 单次写入多少
totalBytesWritten 已经写入了多少
totalBytesExpectedToWrite 文件总大小
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
//打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
//暂停就是将任务挂起 (暂停)暂停在某位置,并将此位置编程全局变量,以便于进行断点续传
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//保存已下载的数据
self.resumeData = resumeData;
}];
//可以使用ResumeData创建任务 (继续),从某位置继续下载
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
//开启继续下载
[self.task resume];
2.6版本 支持 iOS7以上,而且支持NSURLConnectionOperation
3.0版本 支持 iOS7以上 NSURLConnectionOperation被废弃了
//获取网络请求管理器
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//GET 请求地址
//parameters 请求参数
//success 请求成功的回调方法
//failure 请求失败的回调方法
//responseObject 返回请求成功获得的数据
//AFN 可以帮我们自动解析json
// parameters 一般是字典
NSDictionary * params = @{@"username":@"haha",@"password":@“123"};
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://192.168.1.200/login.php" parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
*将GET 改为POST 则为执行POST请求*
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//改成AFXMLParserResponseSerializer 格式
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
//设置可以响应的类型
// manager.responseSerializer.acceptableContentTypes
[manager GET:@"http://192.168.1.2/train.xml" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
POST 上传地址
parameters 文本参数
constructingBodyWithBlock 上传文件的block,有可能多次调用
success 上传成功
failure 上传失败
[manager POST:@"http://192.168.1.200/post/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
formData 上传的数据
FileData 上传文件的data
name 上传文件的key
FileURL 本地路径
fileName 服务器上的名字
mimeType 上传资源的类型
NSURL * url = [[NSBundle mainBundle] URLForResource:@"111.png" withExtension:nil];
//上传文件
[formData appendPartWithFileURL:url name:@"userfile00" fileName:@"2016030211459.png" mimeType:@"image/png" error:NULL];
//上传data
[formData appendPartWithFileData:data name:@"userfile00" fileName:@"123" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
3.0版本删除了所有的 NSURLConnection 方法
并将所有的AFHTTPRequestOperationManager 改为 AFHTTPSessionManager
AFHTTPSessionManager * manager1 = [AFHTTPSessionManager manager];
AFURLSessionManager *manager2 = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
AFURLSessionManager ≈ NSURLSession
设置manager2的同时需要设置NSURLSessionConfiguration
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@“,AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://192.168.1.200/post/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:[[NSBundle mainBundle] URLForResource:@"111.png" withExtension:nil] name:@"userfile00" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:[@"http://192.168.1.2/demo.json" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//下载地址
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSLog(@"%@",[documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]);
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
{
NSLog(@"File downloaded to: %@", filePath);
}];
//filePath == [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]
[downloadTask resume];