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

请求下来的部分数据:

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

相关推荐
wahkim2 小时前
移动端开发工具集锦
flutter·ios·android studio·swift
2501_916007473 小时前
提升 iOS 26 系统流畅度的实战指南,多工具组合监控
android·macos·ios·小程序·uni-app·cocoa·iphone
wangxiaosu3 小时前
macos安装、更新、使用homebrew
macos·homebrew
hellojackjiang20115 小时前
全面适配iOS 26液态玻璃,基于开源IM即时通讯框架MobileIMSDK:RainbowChat-iOS端v10.2发布
ios·网络编程·即时通讯·im开发·rainbowchat
心灵宝贝5 小时前
Mac版PDF Squeezer v4.5.1安装教程(DMG文件下载+详细步骤)
macos
非专业程序员Ping8 小时前
一文读懂字符、字形、字体
ios·swift·font
2501_915921439 小时前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
日日行不惧千万里9 小时前
2025最新仿默往 IM 即时通讯系统源码(PC + Web + iOS + Android)完整版发布!
android·ios
歪歪1009 小时前
React Native开发Android&IOS流程完整指南
android·开发语言·前端·react native·ios·前端框架
阿里超级工程师11 小时前
ios云打包证书申请不需要苹果电脑也是可以的
ios·证书·云打包