AFNetworking
对于第三方的用法分析的比较好的博客, 总是有很多, 来源自网络汇总!
1. 下载 AFNetworking(点我)
2. 需要引入的库
- CoreLocation.frameworkGET请求方法
- SystemConfiguration.framework
- MobileCoreServices.framework
- Security.framework
需要在 ARC 的环境下 - 非 ARC 的工程中 - 请添加 -fobjc-arc
3. GET和POST请求
#import "AFNetworking.h"
3.1 GET请求
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
POST请求方法
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
进行封装, 使用的时候使用相应的方法
封装内部GET方法
+ (void)getDataWithUrl:(NSString *)str completion:(void (^)(NSData *))block
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]]; // 利用hash值作为存入本地的文件名,
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 设置管理员
manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 编码格式默认是 NSUTF8StringEncoding
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[manager GET:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"请求成功");
NSString *requsetTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requsetTmp dataUsingEncoding:NSUTF8StringEncoding]];
[resData writeToFile:path atomically:YES];
block(resData);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败");
NSData *pickData = [NSData dataWithContentsOfFile:path];
block(pickData);
}];
}
这样就封装好了 在外部直接调用并进行数据处理
NSString *str = @"https//****************************";
[NetWorkHandle getDataWithUrl:str completion:^(NSData *data) {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]
// 处理JSON数据
}
3.2 POST请求 一样
+ (void)postDataWithUrl:(NSString *)str completion:(void(^)(NSData *data))block
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//
NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath, [str hash]]; // 利用hash值作为存入本地的文件名,
NSLog(@"%@", path);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[manager POST:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *requsetTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requsetTmp dataUsingEncoding:NSUTF8StringEncoding]];
[resData writeToFile:path atomically:YES]; // 写入本地
block(resData);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败");
NSData *pickData = [NSData dataWithContentsOfFile:path]; // 读取本地
block(pickData);
}];
}
外部使用如GET是一样的!
4. 用于监听网络状态
AFNetworkReachabilityStatusUnknown = -1, // 未知
AFNetworkReachabilityStatusNotReachable = 0, // 无连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G
AFNetworkReachabilityStatusReachableViaWiFi = 2, // WiFi
使用
// 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
若是网络中断, 内部会把网络请求的中断, 自己可以设置提醒, 若再次连上网, AFN会自动进行请求;
可以设置弹窗根据不同的网络状态进行不同的提示
-(void)alert:(NSString *)message{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"System Info" message:message delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles: nil];
[alertView show];
}
-(void)checkNetworkStatus{
//创建一个用于测试的url
NSURL *url=[NSURL URLWithString:@"http://www.apple.com"];
AFHTTPRequestOperationManager *operationManager=[[AFHTTPRequestOperationManager alloc]initWithBaseURL:url];
//根据不同的网络状态改变去做相应处理
[operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
[self alert:@"2G/3G/4G Connection."];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[self alert:@"WiFi Connection."];
break;
case AFNetworkReachabilityStatusNotReachable:
[self alert:@"Network not found."];
break;
default:
[self alert:@"Unknown."];
break;
}
}];
//开始监控
[operationManager.reachabilityManager startMonitoring];
}
也可以在这么写
或者直接使用
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
[self alert:@"网络无连接"];
break;
default:[self handleData];
break;
}
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
开始监控, 当然第二种简介方便, 程序启动后只需要启用一次就可以, 它在不断的监控, 但当网络改变的时候, 可调用下边方法了判断当前网络
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
一般开始监控之后, 在用到判断网络的
AFNetworkReachabilityManager *man = [AFNetworkReachabilityManager sharedManager]; if (man.networkReachabilityStatus != 0) {
// 做处理
} else {
按照上边的几种state的数值来 进行网络处理!
}
5. 下载使用
+ (void)sessionDownloadWithUrl:(NSString*)urlStrsuccess:(void(^)(NSURL*fileURL))successfail:(void(^)())fail
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [ [ AFURLSessionManager alloc] initWithSessionConfiguration: config];
NSString*urlString = [urlStrstringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*request = [NSURLRequestrequestWithURL:url];
NSURLSessionDownloadTask*task = [managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL*(NSURL*targetPath,NSURLResponse*response) {
// 指定下载文件保存的路径
// NSLog(@"%@ %@", targetPath, response.suggestedFilename);
// 将下载文件保存在缓存路径中
NSString*cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES)[0];
NSString*path = [cacheDirstringByAppendingPathComponent:response.suggestedFilename];
// URLWithString返回的是网络的URL,如果使用本地URL,需要注意
// NSURL *fileURL1 = [NSURL URLWithString:path];
NSURL*fileURL = [NSURLfileURLWithPath:path];
// NSLog(@"== %@ |||| %@", fileURL1, fileURL);
if(success) {
success(fileURL);
}
returnfileURL;
}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error) {
NSLog(@"%@ %@", filePath, error);
if(fail) {
fail();
}
}];
[taskresume];
}
// 总结于网络 ~~~~ 链接
另外 对于AFNetworking的进一步使用, 请详见以下链接.来源CocoaChina~~~