AFNet上传

  • 上传
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *dict = @{@"username":@"hjs"};
[manager POST:@"http://120.25.226.186:32812/upload" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSURL *url = [NSURL fileURLWithPath:@"/Users/Programer/Desktop/桌面/20140701231656_tfNAZ.jpeg"];
[formData appendPartWithFileURL:url name:@"file" error:nil];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSDictionary *res = responseObject;
NSLog(@"%@",res);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (error) {
NSLog(@"失败");
}
}];
  • 下载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"]];
NSProgress *progress = nil;
NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSString *cacheP = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *path = [cacheP stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@",path);
NSURL *url = [NSURL fileURLWithPath:path];
return url;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
}];
//为进度添加观察者
[progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
[task resume];
  • get请求
1
2
3
4
5
6
7
8
9
10
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *parameters = @{
@"username":@"hjsit",
@"pwd":@"hjsit"
};
[manager GET:@"http://120.25.226.186:32812/login" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"%@",[responseObject class]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
  • 监听网络状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 1.创建网络监听管理者对象
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
// 2.设置监听
/*
AFNetworkReachabilityStatusUnknown = -1, 未识别
AFNetworkReachabilityStatusNotReachable = 0, 未连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, 3G
AFNetworkReachabilityStatusReachableViaWiFi = 2, wifi
*/
[manager setReachabilityStatusChangeBlock:^ void(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"未连接");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"手机自带网络");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi网络");
break;
default:
NSLog(@"未识别");
break;
}
}];
// 3.开启监听
[manager startMonitoring];
  • 序列化,数据返回类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 1.创建网络管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.利用网络管理者发送get请求
// NSDictionary *parameters = @{
// @"username":@"hjsit",
// @"pwd":@"hjsit",
// @"type":@"XML"
// };
[AFJSONResponseSerializer serializer].acceptableContentTypes = [NSSet setWithObject:@"text/xml"];
// 告诉AFN, 将返回的数据当做JSON来处理
// manager.responseSerializer = [AFJSONRequestSerializer serializer];
// 告诉AFN, 将返回的数据当做XML来处理
// manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
// 告诉AFN, 将返回的数据当做二进制来数据 (服务器返回什么就是什么)
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://120.25.226.186:32812/resources/images/minion_02.png" parameters:nil success:^ void(NSURLSessionDataTask * task, id responseObject) {
NSLog(@"请求成功 %@", [responseObject class]);
} failure:^ void(NSURLSessionDataTask * operation, NSError * error) {
NSLog(@"请求失败 %@", error);
}];
  • AFN推荐继承,推荐使用initWithBaseURL,单例
1
2
3
4
5
6
7
8
9
10
11
12
+ (instancetype)shareNetworkTools2
{
static XMGNetworkTools2 *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/"];
instance = [[self alloc] initWithBaseURL:url sessionConfiguration:cfg];
});
return instance;
}
  • AFN已经封装了HTTPS证书授权代码,直接可以请求,下面是证书授权代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
*
只要请求的地址是HTTPS的, 就会调用这个代理方法
我们需要在该方法中告诉系统, 是否信任服务器返回的证书
Challenge: 挑战 质问 (包含了受保护的区域)
protectionSpace : 受保护区域
NSURLAuthenticationMethodServerTrust : 证书的类型是 服务器信任
*/
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
// NSLog(@"didReceiveChallenge %@", challenge.protectionSpace);
NSLog(@"%@", challenge.protectionSpace.authenticationMethod);
// 1.判断服务器返回的证书类型, 是否是服务器信任
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"是服务器信任的证书");
/*
NSURLSessionAuthChallengeUseCredential = 0, 使用证书
NSURLSessionAuthChallengePerformDefaultHandling = 1, 忽略证书(默认的处理方式)
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 忽略书证, 并取消这次请求
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 忽略当前这一次, 下一次再询问
*/
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential , credential);
}
}