博客> 封装 AFNetWorking 网络请求框架
封装 AFNetWorking 网络请求框架
2019-06-26 20:10 评论:0 阅读:892 Cean_alloc
ios 网络请求 AFNetworking 上传图片 缓存网络数据

封装 AFNetWorking 框架, 包括网络请求, 图片上传, 网络数据缓存, 证书校验... 直接上代码

#import <Foundation>

typedef void(^HandlerBlock)(id responseObj, NSError *error);

@interface XQBaseNetworking : NSObject

@property (nonatomic, readonly, getter=isOnline) BOOL online;

+ (XQBaseNetworking *)sharedNetworking;

+ (void)startMonitoring;

+ (id)GET:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler;

+ (id)POST:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler;

// 图片上传
+ (id)POSTUploadImages:(NSArray *)images path:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler;

// 静默获取数据, 没有提示框
+ (id)silentGET:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler;

// 全路径, 不需要拼 baseURL
+ (id)fullPathGET:(NSString *)fullPath parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler;

- (void)relogin;

@end
#import "XQBaseNetworking.h"
#import <AFNetworkActivityIndicatorManager>
#import "AppDelegate.h"
#import "XQTabBarController.h"

@implementation XQBaseNetworking

+ (XQBaseNetworking *)sharedNetworking {
    static XQBaseNetworking *sharedNetworking = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate,^{
        sharedNetworking = [[self alloc] init];
    });
    return sharedNetworking;
}

+ (void)startMonitoring {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        XQLog(@"%@", AFStringFromNetworkReachabilityStatus(status));
    }];
    [manager startMonitoring];

    /****  所有通过AF发送的请求, 都会在电池条上出现菊花提示  ***/
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
}

// 判断当前是否在线
- (BOOL)isOnline {
    return [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN || [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
}

- (AFHTTPSessionManager *)baseHttpsRequest {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSString *token = kUserDefaultsGetObJectForKey(kXQUserTokenKey);
    XQLog(@"\n请求时附带的 token:%@", token);
    [manager.requestSerializer setValue:kStringNotNil(token) forHTTPHeaderField:kXQUserTokenKey];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"platform"];

    AFJSONResponseSerializer *jsonRes = [AFJSONResponseSerializer serializer];
    jsonRes.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/json", @"text/javascript", @"text/plain", @"application/json", nil];
    manager.responseSerializer = jsonRes;
//    jsonRes.removesKeysWithNullValues = YES;

    // 超时时间
    [manager.requestSerializer setTimeoutInterval:20.f];

    // 校验证书
    //    [manager setSecurityPolicy:[self customSecurityPolicy]];

    return manager;
}

- (AFSecurityPolicy *)customSecurityPolicy {
    // AFSSLPinningModeCertificate 使用证书验证模式, 还未导入证书
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    securityPolicy.allowInvalidCertificates = NO;
//    securityPolicy.validatesDomainName = YES;
    return securityPolicy;
}

#pragma mark - Request

+ (id)GET:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {
    return  [[self alloc] getDataWithPath:path parameters:parameters completionHandler:completionHandler];
}

- (id)getDataWithPath:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {

    [XQProgressHUD showWithStatus:@"加载中..."];

    NSString *baseUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];

    XQLog(@"get请求地址:\n%@\n参数: %@", path, parameters);
    XQLog(@"BaseUrl----%@", baseUrl);

    AFHTTPSessionManager *manager = [self baseHttpsRequest];

    return [manager GET:baseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [XQProgressHUD dismiss];

        if ([responseObject[kCodeKey] integerValue] == 9999) { // token失效, 重登陆

            [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
            [self relogin];

        } else if (1 == [responseObject[kSuccessKey] intValue]) {
            //做缓存
            //            [self saveCacheData:responseObject toPath:task.currentRequest.URL.absoluteString.md5String];

            !completionHandler ?: completionHandler(responseObject, nil);

        } else {
            [self showAlertWithObject:responseObject];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XQProgressHUD dismiss];
        XQLog(@"请求失败 %@, %ld", error.localizedDescription, error.code);
//        [[NSOperationQueue new] addOperationWithBlock:^{
//            //请求失败,读缓存
//            id responseObj = [self readCacheDataFromPath:task.currentRequest.URL.absoluteString.md5String];
//            
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                if (responseObj) {
//                    XQLog(@"请求失败, 读取缓存: %@", responseObj);
//                    !completionHandler ?: completionHandler(responseObj, nil);
//                }else {
        [self showErrorMessage:error];

                    !completionHandler ?: completionHandler(nil, error);
//                }
//            }];
//        }];

    }];
}

+ (id)silentGET:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {
    return [[self alloc] silentGetDataWithPath:path parameters:parameters completionHandler:completionHandler];
}

- (id)silentGetDataWithPath:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {

    NSString *baseUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];

    XQLog(@"get请求地址:\n%@\n参数: %@", path, parameters);
    XQLog(@"BaseUrl----%@", baseUrl);

    AFHTTPSessionManager *manager = [self baseHttpsRequest];

    return [manager GET:baseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (1 == [responseObject[kSuccessKey] intValue]) {
            !completionHandler ?: completionHandler(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XQLog(@"请求失败: %@", error.localizedDescription);
        !completionHandler ?: completionHandler(nil, error);
    }];

}

+ (id)fullPathGET:(NSString *)fullPath parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {
    return [[self alloc] fullPathGET:fullPath parameters:parameters completionHandler:completionHandler];
}

- (id)fullPathGET:(NSString *)fullPath parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {

    XQLog(@"get请求地址:\n%@\n参数: %@", fullPath, parameters);

    AFHTTPSessionManager *manager = [self baseHttpsRequest];

    return [manager GET:fullPath parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        if (1 == [responseObject[kSuccessKey] intValue]) {
            !completionHandler ?: completionHandler(responseObject, nil);
        } else {
            [self showAlertWithObject:responseObject];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XQLog(@"请求失败: %@", error.localizedDescription);
        !completionHandler ?: completionHandler(nil, error);
    }];

}

+ (id)POST:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(void (^)(id, NSError *))completionHandler {
    return [[self alloc] postDataWithPath:path parameters:parameters completionHandler:completionHandler];
}

- (id)postDataWithPath:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {

    [XQProgressHUD showWithStatus:@"加载中..."];

    NSString *baseUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];

    XQLog(@"get请求地址:\n%@\n参数: %@", path, parameters);
    XQLog(@"BaseUrl----%@", baseUrl);

    AFHTTPSessionManager *manager = [self baseHttpsRequest];

    return [manager POST:baseUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [XQProgressHUD dismiss];

        if ([responseObject[kCodeKey] integerValue] == 9999) {

            [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
            [self relogin];

        } else if (1 == [responseObject[kSuccessKey] intValue]) {
            //做缓存
            //            [self saveCacheData:responseObject toPath:task.currentRequest.URL.absoluteString.md5String];

            !completionHandler ?: completionHandler(responseObject, nil);

        } else {
            [self showAlertWithObject:responseObject];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XQProgressHUD dismiss];

//        [[NSOperationQueue new] addOperationWithBlock:^{
//            //请求失败,读缓存
//            id responseObj = [self readCacheDataFromPath:task.currentRequest.URL.absoluteString.md5String];
//            
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                if (responseObj) {
//                    XQLog(@"请求失败, 读取缓存: %@", responseObj);
//                    !completionHandler ?: completionHandler(responseObj, nil);
//                }else {
                    [self showErrorMessage:error];
                    !completionHandler ?: completionHandler(nil, error);
//                }
//            }];
//        }];

    }];
}

+ (id)POSTUploadImages:(NSArray *)images path:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {
    return [[self alloc] uploadImages:images path:path parameters:parameters completionHandler:completionHandler];
}

- (id)uploadImages:(NSArray *)images path:(NSString *)path parameters:(NSDictionary *)parameters completionHandler:(HandlerBlock)completionHandler {

    [XQProgressHUD showWithStatus:@"上传中..."];

    NSString *baseUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];

    XQLog(@"get请求地址:\n%@\n参数: %@", path, parameters);
    XQLog(@"BaseUrl----%@", baseUrl);

    AFHTTPSessionManager *manager = [self baseHttpsRequest];

    return [manager POST:baseUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        for (int i = 0; i < [images count]; i++) {
            UIImage *image = images[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            XQLog(@"图片大小 = %.2fM", (imageData.length * 1.0) / (1024 * 1024));
            NSString *name = [NSString stringWithFormat:@"file%li.jpg", (long)i];
            NSString *filename = [NSString stringWithFormat:@"uploadfile%li.jpg", (long)i];
            [formData appendPartWithFileData:imageData name:name fileName:filename mimeType:@"image/jpeg"];
        }

    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        CGFloat percent = uploadProgress.completedUnitCount * 1.0 / uploadProgress.totalUnitCount;
        XQLog(@"已上传:%.0f%%", (uploadProgress.completedUnitCount * 1.0 / uploadProgress.totalUnitCount) * 100);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [XQProgressHUD dismiss];

        if ([responseObject[kCodeKey] integerValue] == 9999) {

            [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
            [self relogin];

        } else if (1 == [responseObject[kSuccessKey] intValue]) {
            !completionHandler ?: completionHandler(responseObject, nil);
        } else {
            [self showAlertWithObject:responseObject];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [XQProgressHUD dismiss];
        [self showErrorMessage:error];
        !completionHandler ?: completionHandler(nil, error);
    }];

}

#pragma mark - FinishRequestHandler

- (void)relogin {

    kUserDefaultsRemoveObjectForKey(kXQUserTokenKey);
    [XQUserDefaults setBool:NO forKey:kXQUserIsLoginKey];
    [XQUserDefaults synchronize];

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    XQTabBarController *tabBarVC = (XQTabBarController *)appDelegate.window.rootViewController;
    tabBarVC.tabBar.hidden = YES;
    [appDelegate login];
}

//- (void)saveCacheData:(id)data toPath:(NSString *)path {
//    NSString *docPath = kDocumentPath;
//    NSString *cachaPath = [docPath stringByAppendingPathComponent:path];
//    [[NSOperationQueue new] addOperationWithBlock:^{
//        [NSKeyedArchiver archiveRootObject:data toFile:cachaPath];
//    }];
//}

//- (id)readCacheDataFromPath:(NSString *)path {
//    NSString *docPath = kDocumentPath;
//    NSString *cachaPath = [docPath stringByAppendingPathComponent:path];
//    id data = [NSKeyedUnarchiver unarchiveObjectWithFile:cachaPath];
//    return data;
//}

- (void)showErrorMessage:(NSError *)error {
    if (error.code != 3840) {
        if (error.code == -1009) {
            [XQProgressHUD showImage:[UIImage imageNamed:@"unConnect"] status:@"网络异常"];
        } else {
            [XQProgressHUD showImage:[UIImage imageNamed:@"unConnect"] status:error.localizedDescription];
        }
    }
}

- (void)showAlertWithObject:(id)responseBody {
    BOOL empty = [responseBody[@"msg"] isKindOfClass:[NSNull class]] || [responseBody[@"msg"] isEqual:[NSNull null]] || (responseBody[@"msg"] == nil);
    NSString *msg = empty ? @"没有数据" : responseBody[@"msg"];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alertC addAction:sureAction];
    [kAppRootVC presentViewController:alertC animated:YES completion:nil];
}

@end
收藏
1
sina weixin mail 回到顶部