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

请求下来的部分数据:

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

相关推荐
我是谁的程序员11 小时前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
后端·ios
sweet丶12 小时前
微信Matrix 卡顿监控原理梳理与图解
ios
2501_9160074714 小时前
iOS开发中抓取HTTPS请求的完整解决方法与步骤详解
android·网络协议·ios·小程序·https·uni-app·iphone
ZZH_AI项目交付18 小时前
我把 AI 最容易改坏真实 App 的地方,整理成了 skills
人工智能·ios·app
00后程序员张19 小时前
Windows 下怎么生成 AppStoreInfo.plist?不依赖 Xcode 的方法
ide·macos·ios·小程序·uni-app·iphone·xcode
原鸣清19 小时前
iOS 自定义 Markdown 渲染实践:从成品库到可魔改 Demo
ios
Daniel_Coder19 小时前
iOS Widget 开发-18:Widget 的 SwiftUI 视图适配与设计
ios·swiftui·swift·widget·widgetcenter
Daniel_Coder19 小时前
iOS Widget 开发-17:Widget 错误处理与空状态设计
ios·swift·widget·widgetcenter
wjm04100620 小时前
简单谈谈ios开发中的UI
开发语言·ios·swift
boldiy21 小时前
如何在MAC电脑中实现自动切换windows快捷键
windows·macos