官方建议AFN的使用方法
1. 定义一个全局的AFHttpClient:包含有
1> baseURL
2> 请求
3> 操作队列 NSOperationQueue
2. 由AFHTTPRequestOperation负责所有的网络操作请求
0.导入框架准备工作•1. 将框架程序拖拽进项目
•2. 添加iOS框架引用
–SystemConfiguration.framework
–MobileCoreServices.framework
•3. 引入#import "AFNetworking.h"
4. 修改xxx-Prefix.pch文件
#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
1.AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理1@interfaceViewController ()23{45//AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理67AFHTTPClient *_httpClient;17NSOperationQueue *_queue;1819}
1- (void)viewDidLoad2{3[super viewDidLoad];45NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"];6_httpClient =[[AFHTTPClient alloc] initWithBaseURL:url];78_queue =[[NSOperationQueue alloc] init];9}
2.利用AFN实现文件上传操作细节1#pragmamark - 文件上传2-(IBAction)uploadImage3{4/*5此段代码如果需要修改,可以调整的位置671. 把upload.php改成网站开发人员告知的地址82. 把file改成网站开发人员告知的字段名9*/10//1. httpClient->url1112//2. 上传请求POST13NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST"path:@"upload.php"parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData) {14//在此位置生成一个要上传的数据体15//form对应的是html文件中的表单161718UIImage *image = [UIImage imageNamed:@"头像1"];19NSData *data =UIImagePNGRepresentation(image);2021//在网络开发中,上传文件时,是文件不允许被覆盖,文件重名22//要解决此问题,23//可以在上传时使用当前的系统事件作为文件名24NSDateFormatter *formatter =[[NSDateFormatter alloc] init];25//设置时间格式26formatter.dateFormat =@"yyyyMMddHHmmss";27NSString *str =[formatter stringFromDate:[NSDate date]];28NSString *fileName = [NSString stringWithFormat:@"%@.png", str];293031/*32此方法参数331. 要上传的[二进制数据]342. 对应网站上[upload.php中]处理文件的[字段"file"]353. 要保存在服务器上的[文件名]364. 上传文件的[mimeType]37*/38[formData appendPartWithFileData:data name:@"file"fileName:fileName mimeType:@"image/png"];39}];4041//3. operation包装的urlconnetion42AFHTTPRequestOperation *op =[[AFHTTPRequestOperation alloc] initWithRequest:request];4344[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,idresponSEObject) {45NSLog(@"上传完成");46} failure:^(AFHTTPRequestOperation *operation, NSError *error) {47NSLog(@"上传失败->%@", error);48}];4950//执行51[_httpClient.operationQueue addOperation:op];
作者: 清澈Saup
出处: http://www.cnblogs.com/qingche/
本文版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文连接。