一、AFNetWorking基本使用
//
// ViewController.m
// IOS_0112_AFNetWorking
//
// Created by ma c on 16/2/11.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import "AFNetworking.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self getData];
} - (void)postJSON
{
// 1.创建一个请求操作管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.声明:等会服务器返回的是JSON数据,默认是JSON数据
mgr.responseSerializer = [AFJSONResponseSerializer serializer]; // 2.请求参数
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"";
dict[@"pwd"] = @"";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr POST:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//判断responseObject的类型
//NSLog(@"请求成功-----%@",[responseObject class]);
NSLog(@"请求成功-----%@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}]; } - (void)getData
{
// 1.创建一个请求操作管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.声明:不要对服务器返回的数据进行解析,直接返回data即可
mgr.responseSerializer = [AFHTTPResponseSerializer serializer]; // 2.请求参数
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"";
dict[@"pwd"] = @"";
//dict[@"type"] = @"XML";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"请求成功-----%@", [responseObject class]); NSDictionary *dcit = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dict); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}]; }
- (void)getXML
{
// 1.创建一个请求操作管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.声明:等会服务器返回的是XML数据
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
// 2.请求参数
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"";
dict[@"pwd"] = @"";
dict[@"type"] = @"XML";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"请求成功-----%@", responseObject);
//解析XML数据 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}]; }
- (void)getJSON
{
// 1.创建一个请求操作管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.声明:等会服务器返回的是JSON数据,默认是JSON数据
mgr.responseSerializer = [AFJSONResponseSerializer serializer]; // 2.请求参数
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"";
dict[@"pwd"] = @"";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr GET:url parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//判断responseObject的类型
//NSLog(@"请求成功-----%@",[responseObject class]);
NSLog(@"请求成功-----%@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}]; }
@end
二、AFNetWorking文件上传
//
// ViewController.m
// IOS_0112_AFNetWorking
//
// Created by ma c on 16/2/11.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import "AFNetworking.h" @interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView; - (IBAction)upload; @end @implementation ViewController /*
文件下载,文件比较大时,断点续传技术:普遍所有的HTTP服务器都支持
文件上传,文件比较大时,断点续传技术:一般的HTTP服务器都不支持,常用的技术是Socket(TCP\IP,UDP)
*/ - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self uploadPhotos];
} - (void)uploadPhotos
{
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
[sheet showInView:self.view.window]; // if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
// //上传手机照片给服务器,图片来源
// // 拍照:UIImagePickerControllerSourceTypeCamera
// // 相册:UIImagePickerControllerSourceTypePhotoLibrary
//
// UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// //设置图片来源
// //ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
// ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// //设置代理
// ipc.delegate = self;
// [self presentViewController:ipc animated:nil completion:nil];
} #pragma mark - UIActionSheetDelegate的代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
//设置代理
ipc.delegate = self; switch (buttonIndex) {
case : //拍照
{
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
break;
}
case : //相片
{
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
break;
} default:
break;
}
//显示控制器
[self presentViewController:ipc animated:nil completion:nil];
} #pragma mark - UIImagePickerControllerDelegate代理方法
//选择完图片后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//销毁控制器
[picker dismissViewControllerAnimated:nil completion:nil];
//获得图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
//显示图片
self.imageView.image = image;
NSLog(@"%@",image); } - (IBAction)upload {
if (self.imageView.image == nil) return; // 1.创建一个请求操作的管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.封装参数(此参数只能放非文件参数)
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"bowen";
dict[@"pwd"] = @""; // 2.发送一个请求
NSString *url = @"http://localhost:8080/MJServer/upload"; [mgr POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { /*
FileData:需要上传文件的具体数据
name:服务器那边接收文件用的参数名
fileName:告诉服务器所上传文件的文件名
mimeType:所上传文件的文件类型
*/ NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
[formData appendPartWithFileData:fileData name:@"file" fileName:@"pic.jpg" mimeType:@"image/jpeg"]; } progress:^(NSProgress * _Nonnull uploadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上传成功");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传失败");
}]; } #pragma mark - uploadFile
- (void)uploadFile
{
// 1.创建一个请求操作的管理者
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 2.封装参数(此参数只能放非文件参数)
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"bowen";
dict[@"pwd"] = @""; // 2.发送一个请求
NSString *url = @"http://localhost:8080/MJServer/upload"; [mgr POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//在发送请求之前会自动调用这个block
//需要在这个block中添加文件参数到formData /*
FileURL:需要上传的文件的URL路径
name:告诉服务器那边接收文件用的参数名
fileName:告诉服务器所上传文件的文件名
mimeType:所上传文件的文件类型
*/
NSURL *url = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"jpg"];
[formData appendPartWithFileURL:url name:@"file" fileName:@"text.jpg" mimeType:@"image/jpeg"error:nil]; /*
FileData:需要上传文件的具体数据
name:服务器那边接收文件用的参数名
fileName:告诉服务器所上传文件的文件名
mimeType:所上传文件的文件类型 UIImage *image = [UIImage imageNamed:@"abc"];
NSData *fileData = UIImageJPEGRepresentation(image, 1);
[formData appendPartWithFileData:fileData name:@"file" fileName:@"pic.jpg" mimeType:@"image/jpeg"]; */ } progress:^(NSProgress * _Nonnull uploadProgress) {
;
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上传成功");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传失败");
}];
} @end