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

请求下来的部分数据:

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

相关推荐
whyfail1 小时前
Colima:把 Docker Desktop 从 Mac 上“瘦身”的那把刀
macos·docker·容器
2501_915918412 小时前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview
他们都不看好你,偏偏你最不争气3 小时前
【iOS】Runtime - Part 1 && 对象与类的本质
macos·ios·objective-c·cocoa
黑科技iOS上架4 小时前
Swift6.0多线程特性注意事项
ios
黑科技iOS上架5 小时前
实测iOS深度混淆工具过审4.3、2.3.1能力
经验分享·ios
Shacoray6 小时前
Mac 向 Windows 局域网传文件方案整理
windows·macos
mxpan20 小时前
macOS 13+ 上使用 macFUSE + NTFS-3G 读写 NTFS 移动硬盘技术说明
macos·策略模式
鹤卿12321 小时前
(OC)UI学习——网易云仿写
ui·ios·objective-c
不自律的笨鸟21 小时前
最新屏蔽 iOS 系统更新描述文件保姆级教程
ios