【iOS】将网络请求封装在一个单例类Manager中(AFNetworking、JSONModel)

项目开发中会请求大量不同的API,若将网络请求三板斧直接写在Controller中会代码十分冗杂,干脆直接将AFNetWorkingJSONModel封装到一个全局的Manager单例类中,在Manager类中进行网络请求和数据解析

导入AFNetworking和JSONModel

参考【iOS】AFNetworking的基本使用

创建一个单例类Manager

Manager.h

代码块Block用于传值

objectivec 复制代码
#import <Foundation/Foundation.h>
#import "TestModel.h"

typedef void(^SuccessBlock)(TestModel* testModel);
typedef void(^ErrorBlock)(NSError* error);

@interface Manager : NSObject

+ (instancetype)sharedManager;

- (void)sendRequestWithURL: (NSString *)urlString success: (SuccessBlock)success failure: (ErrorBlock)failure;

@end

Manager.m

这里使用GCD方法实现简单的单例模式

objectivec 复制代码
#import "Manager.h"
#import "AFNetworking.h"

static Manager* manager = nil;

@implementation Manager

+ (instancetype)sharedManager {
    if (!manager) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[Manager alloc] init];
        });
    }
    
    return manager;
}

- (void)sendRequestWithURL:(NSString *)urlString success:(SuccessBlock)success failure:(ErrorBlock)failure {
    
    [[AFHTTPSessionManager manager] GET: urlString parameters: nil headers: nil progress: nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            TestModel* testModel = [[TestModel alloc] initWithDictionary: responseObject error: nil];
            success(testModel);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end

Manager的使用

objectivec 复制代码
- (void)requestTest {
    [[Manager sharedManager] sendRequestWithURL: @"https://news-at.zhihu.com/api/4/news/latest" success:^(TestModel * _Nonnull testModel) {
            NSLog(@"%@", testModel.stories[0]);
        } failure:^(NSError * _Nonnull error) {
            if (error) NSLog(@"请求失败");
        }];
}

请求下来的部分数据:

这样就可以将不同的请求分别写成不同的单例方法,而且代码简单易懂

相关推荐
小溪彼岸2 小时前
macOS自带截图命令ScreenCapture
macos
法的空间6 小时前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
2501_915918417 小时前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
TESmart碲视8 小时前
Mac 真正多显示器支持:TESmart USB-C KVM(搭载 DisplayLink 技术)如何实现
macos·计算机外设·电脑
00后程序员张9 小时前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
Magnetic_h17 小时前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
00后程序员张19 小时前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
前端小超超19 小时前
capacitor配置ios应用图标不同尺寸
ios·蓝桥杯·cocoa
2501_9151063221 小时前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
kymjs张涛1 天前
零一开源|前沿技术周刊 #16
ios·apple·hacker news