【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(@"请求失败");
        }];
}

请求下来的部分数据:

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

相关推荐
如此风景17 分钟前
SwiftUI 状态管理详解
ios
QuantumLeap丶23 分钟前
《Flutter全栈开发实战指南:从零到高级》- 25 -性能优化
android·flutter·ios
游戏开发爱好者84 小时前
H5 混合应用加密 Web 资源暴露到 IPA 层防护的完整技术方案
android·前端·ios·小程序·uni-app·iphone·webview
咨询qq 8762239654 小时前
多源动态最优潮流分布式鲁棒优化探索
cocoa
2501_915106325 小时前
最新版本iOS系统设备管理功能全面指南
android·macos·ios·小程序·uni-app·cocoa·iphone
游戏开发爱好者85 小时前
HTTPS DDoS 排查 异常流量到抓包分析
网络协议·ios·小程序·https·uni-app·iphone·ddos
TouchWorld5 小时前
iOS逆向-哔哩哔哩增加3倍速播放(3)-[横屏视频-全屏播放]场景
ios·swift
2501_915918416 小时前
iOS 性能监控 运行时指标与系统行为的多工具协同方案
android·macos·ios·小程序·uni-app·cocoa·iphone
TheNextByte16 小时前
适用于Windows和Mac电脑的Android文件传输工具
windows·macos·电脑