YTKNetwork is a high level request util based on AFNetworking.

Overview

YTKNetwork

License MIT Pod version Carthage Compatible Platform info Build Status

What

YTKNetwork is a high level request util based on AFNetworking. It's developed by the iOS Team of YuanTiKu. It provides a High Level API for network request.

YTKNetwork is used in all products of YuanTiKu, including: YuanTiKu, YuanSoTi, YuanFuDao, FenBiZhiBoKe.

中文说明

Features

  • Response can be cached by expiration time
  • Response can be cached by version number
  • Set common base URL and CDN URL
  • Validate JSON response
  • Resume download
  • block and delegate callback
  • Batch requests (see YTKBatchRequest)
  • Chain requests (see YTKChainRequest)
  • URL filter, replace part of URL, or append common parameter 
  • Plugin mechanism, handle request start and finish. A plugin for show "Loading" HUD is provided

Who

YTKNetowrk is suitable for a slightly more complex project, not for a simple personal project.

YTKNetwork is helpful if you want to cache requests, manage the dependences of requests, or validate the JSON response. And if you want to cache requests based on request version, this is one of the greatest advantages of YTKNetwork.

Why 

YTKNetwork provides YTKRequest to handle every network request. You should inherit it and override some methods to define custom requests in your project.

The main idea is use the Command Pattern. The benefits are:

  • Your code is decoupled to detail network request framework, it's easy to replace it. Actually, YTKNetwork is originally based on ASIHttpRequest, we just spent two days to switch to AFNetworking.
  • Handle common logic in base class.
  • Easier Persistence

But YTKNetwork is not suitable if your project is very simple. You can use AFNetworking directly in controller.

Installation

To use YTKNetwork add the following to your Podfile

pod 'YTKNetwork'

Or add this in your Cartfile:

github "yuantiku/YTKNetwork" ~> 3.0

Requirements

YTKNetwork Version AFNetworking Version Minimum iOS Target Note
3.x 4.x iOS 9 Xcode 11+ is required.
2.x 3.x iOS 7 Xcode 7+ is required.
1.x 2.x iOS 6 n/a

YTKNetwork is based on AFNetworking. You can find more detail about version compatibility at AFNetworking README.

Guide & Demo

Contributors

Acknowledgements

Thanks for their great work.

License

YTKNetwork is available under the MIT license. See the LICENSE file for more info.

Comments
  • SOS help  please

    SOS help please

    Finished Request: UserLogInRequest 2016-10-13 18:13:07.042020 loveOil[895:116373] Request UserLogInRequest failed, status code = 200, error = (null)

    why all the request Response this log help

    -(YTKResponseSerializerType)responseSerializerType { return YTKResponseSerializerTypeJSON; }

    并没有用啊

    opened by SummerHF 13
  • YTKRequest _cache 有个bug

    YTKRequest _cache 有个bug

    前提开启缓存

    UserApi *api = [UserApi new]
    if([api cacheJson]){
     .....
    }
    [api start];
    

    [api cacheJson] 这句代码会让 YTKRequest _cache有值。 [api start];该代码执行完毕后,会掉[self responseJSONObject]获取返回对象 源代码中

    - (id)responseJSONObject {
        if (_cacheJson) {
            return _cacheJson;
        } else {
            return [super responseJSONObject];
        }
    }
    

    这样的话,会返回_cache 的内容,而不是最新返回的 [super responseJSONObject]数据 YTKRequest 在这里个文件里面,没有找到在请求回来后,对cache值的更新,或者置空。

    我修改了源码

    - (void)saveJsonResponseToCacheFile:(id)jsonResponse {
        if ([self cacheTimeInSeconds] > 0 && ![self isDataFromCache]) {
            _cacheJson = jsonResponse;====添加了改代码
            NSDictionary *json = jsonResponse;
            if (json != nil) {
                [NSKeyedArchiver archiveRootObject:json toFile:[self cacheFilePath]];
                [NSKeyedArchiver archiveRootObject:@([self cacheVersion]) toFile:[self cacheVersionFilePath]];
            }
        }
    }
    

    是否我的理解有误,还是其他的原因。我的修改方案的是否合理可行。。 希望能得到回复

    opened by wzi90921 13
  • 接口直接走到失败的block,但是responseString是对的

    接口直接走到失败的block,但是responseString是对的

    使用方法 startWithCompletionBlockWithSuccess 直接进了failure:^(YTKBaseRequest *request) 的block

    Request MSRequest failed, status code = 200, error = (null) (lldb) po request.responseString {"status":0,"msg":"ok","data":{"pageNo":"1","rows":"20","total_nums":"285","list":[{"tid":"379","city":"北京","type":"0","keyword":"全部

    opened by gank0326 11
  • Status Code = 0 的问题

    Status Code = 0 的问题

    初次使用YTKNetwork,调用原来工程中的App的时候,发现在回调的地方

    BOOL result = [request statusCodeValidator];
    
    - (BOOL)statusCodeValidator {
        NSInteger statusCode = [self responseStatusCode];
        if (statusCode >= 200 && statusCode <=299) {
            return YES;
        } else {
            return NO;
        }
    }
    - (NSInteger)responseStatusCode {
        return self.requestOperation.response.statusCode;
    }
    

    这里返回的statusCode为0,导致框架中判断result=NO,请求失败。 但是实际上请求是成功了,请求的数据也拿到了。

    opened by junwangInChina 11
  • 并发请求回调问题

    并发请求回调问题

    我这边是这样的, 我把 YTK 和我的具体业务逻辑层做了一个二次封装 首先是 1 ran'h 然后做了一个 Manage 的类用来统一处理 Token 和回调的问题,如: 2

    现在出现的问题是, 我在两个页面注册同一个监听登录成功的通知,每当用户登录成功后就会请求两个列表刷新界面, 这两个请求的代码片段如下: 界面1: 3 界面2: 2016093014752031993590.jpg

    两个数组都是泛型,enquiryArray的数据类型是enquiryMode, 第二个请求的是TradeRecordModel,但是我在第二个界面登陆成功后再第一个界面回调刷新界面的时候会出现这样的错误 20160930147520332029202.jpg

    也即是在得到通知后, 第一个界面和第二界面都会刷新界面, 但是在第一个请求的数组里面的数据却是第二个请求的回调数据... 请问您知道这个是为什么呢? 怎么样解决呢? 是不是因为线程的问题..

    opened by SuooL 10
  • 请求失败的blcok里面怎么还会输出正确数据呢?

    请求失败的blcok里面怎么还会输出正确数据呢?

    第一次使用YTK 真的有点懵逼啊 普通的网络请求 我是直接用一个继承自YTKRequest的类的对象调用startWithCompletionBlockWithSuccess方法 然后block走的是failure部分 但是还是有请求的数据打印出来啊 而且打印了request.requestOperationError信息为null 如果请求成功不是走Success部分么 代码是这样的:

    WYURLCommon *reg = [[WYURLCommon alloc] init];
        reg.ignoreCache = YES;
        [reg startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
            id obj = request.responseJSONObject;
            NSLog(@"success ------- %@" , obj);
        } failure:^(__kindof YTKBaseRequest *request) {
            id obj = request.responseJSONObject;
            NSError *error = request.requestOperationError;
            NSLog(@"failure ------- %@ error --  %@" , obj , error);
        }];`
    

    WYURLCommon继承自YTKRequest 重写了

    - (NSString *)requestUrl - (YTKRequestMethod)requestMethod
    - (YTKRequestSerializerType)requestSerializerType
    

    方法

    opened by lwy121810 10
  • 如何在设置了cacheTimeInSeconds缓存这种情况下更新缓存并获得新的数据

    如何在设置了cacheTimeInSeconds缓存这种情况下更新缓存并获得新的数据

    需求是这样的,设置了cacheTimeInSeconds大于0的,程序先调用缓存数据,再请求,再显示新数据。现在是这么个情况,就是第一次,使用的是缓存数据,start之前设置ignoreCache = YES,取新的请求数据,但是回调还是老的数据,其实这个时候缓存数据已经更新了,所以第二次程序执行的时候先用的缓存数据,所以数据更新了。请问有什么办法,第一次就能获取新的数据呢?

    opened by hnzlk2014 9
  • 你好,AFN更新4.0了,可否也跟进一下。

    你好,AFN更新4.0了,可否也跟进一下。

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    请给出所提出问题的详尽描述,包括具体的错误信息,打印的堆栈等等,以及重现此问题的具体步骤。

    Please fill in the detailed description of the issue (full output of any stack trace, compiler error, ...) and the steps to reproduce the issue.

    opened by zR-Zr 8
  • [YTKNetworkUtils stringEncodingWithRequest:]中发生崩溃

    [YTKNetworkUtils stringEncodingWithRequest:]中发生崩溃

    fabric抓到到崩溃数据。 没找到必现步骤。收集到13份崩溃,机型无规律,iOS 11 70%,iOS 10 30%,没有其他低版本的被收集到,不确定是低版本没问题还是怎样。 #0 Crashed: com.yuantiku.networkagent.processing EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000

    Crashed: com.yuantiku.networkagent.processing 0 CoreFoundation 0x183d17544 CFStringGetCString + 88 1 CoreFoundation 0x183d96594 CFStringConvertIANACharSetNameToEncoding + 124 2 Finance2 0x102d04ba8 +[YTKNetworkUtils stringEncodingWithRequest:] (YTKNetworkPrivate.m:127) 3 Finance2 0x102d0249c -[YTKNetworkAgent handleRequestResult:responseObject:error:] (YTKNetworkAgent.m:322) 4 Finance2 0x102d03410 __113-[YTKNetworkAgent dataTaskWithHTTPMethod:requestSerializer:URLString:parameters:constructingBodyWithBlock:error:]_block_invoke (YTKNetworkAgent.m:458) 5 Finance2 0x102c8bb34 __72-[AFURLSessionManagerTaskDelegate URLSession:task:didCompleteWithError:]_block_invoke_2.150 (AFURLSessionManager.m:308) 6 libdispatch.dylib 0x1837d5088 _dispatch_call_block_and_release + 24 7 libdispatch.dylib 0x1837d5048 _dispatch_client_callout + 16 8 libdispatch.dylib 0x1837dd474 _dispatch_continuation_pop$VARIANT$mp + 588 9 libdispatch.dylib 0x1837dbcd4 _dispatch_async_redirect_invoke$VARIANT$mp + 604 10 libdispatch.dylib 0x1837e21c8 _dispatch_root_queue_drain + 596 11 libdispatch.dylib 0x1837e1f10 _dispatch_worker_thread3 + 120 12 libsystem_pthread.dylib 0x183a7b130 _pthread_wqthread + 1268 13 libsystem_pthread.dylib 0x183a7ac30 start_wqthread + 4

    opened by buyuxing 8
  • 如何接受请求到的json数据?

    如何接受请求到的json数据?

    我写了个类试用了一下,但是不知道如何接受请求到的json数据,返回的数据在responseString里,而不是responseJSONObject里: //.h文件

    import <Foundation/Foundation.h>

    import "YTKRequest.h"

    @interface MeiTuAPI : YTKRequest

    @property (nonatomic, strong) NSNumber *siteID; @property (nonatomic, strong) NSNumber *typeID; @property (nonatomic, strong) NSNumber *styleID; @property (nonatomic, strong) NSNumber *pSize; @property (nonatomic, strong) NSNumber *page;

    @end

    //.m文件

    import "MeiTuAPI.h"

    @implementation MeiTuAPI

    -(instancetype)init{ if (self = [super init]) { self.siteID = @1; self.typeID = nil; self.styleID = nil; self.pSize = @20; self.page = @1; } return self; }

    -(NSString *)baseUrl{ return BaseUrl; }

    -(NSString *)requestUrl{ return Url_amazingPicsList; }

    -(YTKRequestMethod)requestMethod{ return YTKRequestMethodPost; }

    • (id)requestArgument{ NSMutableDictionary *patameters = [NSMutableDictionary dictionary]; if (self.siteID) { [patameters setObject:self.siteID forKey:@"site_id"]; } if (self.typeID) { [patameters setObject:self.typeID forKey:@"type_id"]; } if (self.styleID) { [patameters setObject:self.styleID forKey:@"fg_id"]; } if (self.pSize) { [patameters setObject:self.pSize forKey:@"pSize"]; }else{ [patameters setObject:@20 forKey:@"pSize"]; } if (self.page) { [patameters setObject:self.page forKey:@"p"]; }else{ [patameters setObject:@1 forKey:@"p"]; } return patameters; }

    @end

    //调用

    • (void)loadData{ MeiTuAPI *request = [[MeiTuAPI alloc]init]; request.siteID = @2; request.pSize = @10;

      [request startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) { if (request.responseStatusCode != 0) { NSLog(@"%@",request.responseString); //有数据 NSLog(@"%@",request.responseJSONObject); //返回nil }

      } failure:^(YTKBaseRequest *request) {

      }]; }

    help wanted 
    opened by heyehao2008 8
  • 使用YTKNetwork在ios8.2、8.3、8.4的系统app启动不起来,app直接闪退

    使用YTKNetwork在ios8.2、8.3、8.4的系统app启动不起来,app直接闪退

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    您好,我们app新建的swfit项目是用YTKNetwork作为网络请求的的库,使用carthage集成进来,然后在ios8.2、8.3、8.4的系统模拟器app启动就闪退,而9.0以上的系统运行都没有问题,我们app支持的最低部署版本时8.2的系统,Xcode的奔溃日志信息时下面的内容: dyld: Symbol not found: _NSURLSessionTaskPriorityDefault Referenced from: /Users/romance/Library/Developer/CoreSimulator/Devices/6D9D54BE-C804-4D1A-B9BF-5A91AE51D41E/data/Containers/Bundle/Application/D21360C5-B815-4E43-BA22-1A1351CD8059/FCSBookRoomDemo.app/Frameworks/YTKNetwork.framework/YTKNetwork Expected in: /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 8.3.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation in /Users/romance/Library/Developer/CoreSimulator/Devices/6D9D54BE-C804-4D1A-B9BF-5A91AE51D41E/data/Containers/Bundle/Application/D21360C5-B815-4E43-BA22-1A1351CD8059/FCSBookRoomDemo.app/Frameworks/YTKNetwork.framework/YTKNetwork 项目上线紧急问题,希望能给解决方案!(我们公司测试机只有9.0的设备,以上测试的信息时在模拟器上的,出现这个问题是在项目上线后大量的苹果用户8.3、8.4系统的用户反馈安装app就直接闪退,我们就一个一个查,因为新提交的版本才加入这个网络请求的库,最后锁定的这个问题)

    opened by XcqRomance 7
  • 多线程异步中PUT请求异常

    多线程异步中PUT请求异常

    dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, GlobalQueue, ^{ dispatch_group_enter(group); 这里做YTK请求,进入请求流程后,失败或者成功的结果都没有返回。 dispatch_group_leave(group); } });

    opened by yu910520 0
  • 如何上传多图呢?

    如何上传多图呢?

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    请给出所提出问题的详尽描述,包括具体的错误信息,打印的堆栈等等,以及重现此问题的具体步骤。

    Please fill in the detailed description of the issue (full output of any stack trace, compiler error, ...) and the steps to reproduce the issue.

    opened by 2952883085 0
  • 希望加一个设置HTTPMethodsEncodingParametersInURI入口,或者不要每次都去调用[AFHTTPRequestSerializer serializer](原因:AFN默认把DELETE方式参数拼接在url上,想放在body里)

    希望加一个设置HTTPMethodsEncodingParametersInURI入口,或者不要每次都去调用[AFHTTPRequestSerializer serializer](原因:AFN默认把DELETE方式参数拼接在url上,想放在body里)

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    请给出所提出问题的详尽描述,包括具体的错误信息,打印的堆栈等等,以及重现此问题的具体步骤。

    Please fill in the detailed description of the issue (full output of any stack trace, compiler error, ...) and the steps to reproduce the issue.

    opened by wenlong03 0
  • 多域名 重试

    多域名 重试

    现在有个需求是需要在一个接口请求的时候,如果请求失败,需要切换到另一个域名请求这个接口,请问需要用什么方法,可以快捷的实现这个需求呢?

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    请给出所提出问题的详尽描述,包括具体的错误信息,打印的堆栈等等,以及重现此问题的具体步骤。

    Please fill in the detailed description of the issue (full output of any stack trace, compiler error, ...) and the steps to reproduce the issue.

    opened by Benight 1
  • AFJSONResponseSerializer 的 acceptableContentTypes  希望进行修改 没有发现有类似的 接口提供支持

    AFJSONResponseSerializer 的 acceptableContentTypes 希望进行修改 没有发现有类似的 接口提供支持

    提出问题前请先确认完成了下列几项步骤 New Issue Checklist

    问题描述 Issue Description

    请给出所提出问题的详尽描述,包括具体的错误信息,打印的堆栈等等,以及重现此问题的具体步骤。

    Please fill in the detailed description of the issue (full output of any stack trace, compiler error, ...) and the steps to reproduce the issue.

    opened by stevenchans 0
Releases(3.0.0)
  • 3.0.0(May 6, 2020)

    Upgrade to AFNetworking 4.x,iOS support iOS 9+ (required by AFNetworking 4.x)

    Supported:

    • upload progress
    • add constructingBlock for PUT method
    • add NSURLSessionTaskMetrics block in YTKNetworkConfig
    Source code(tar.gz)
    Source code(zip)
  • 2.1.3(Nov 1, 2019)

    This is a bugfix version.

    Fixed

    • Remove AFNetworking UIKit subspec. (ca6eb73f86bc8d17fe07e42d657bbd354b37a1c9)
    • Random crash in YTKNetworkUtils because of multithread (eb02979959fa319a0e6eed42224abf5505f89222)
    Source code(tar.gz)
    Source code(zip)
  • 2.0.4(Sep 5, 2017)

  • 2.0.3(Nov 3, 2016)

    This is a bugfix version.

    Fixed

    • Clean downloaded file if failed. And overwrite any existing files when downloading (277de203dbd5e8e2f9e8b0565895998a4097557f)
    Source code(tar.gz)
    Source code(zip)
  • 2.0.2(Oct 20, 2016)

  • 2.0.1(Oct 21, 2016)

  • 2.0.0(Oct 21, 2016)

Owner
猿辅导技术团队
猿辅导技术团队
A lightweight but powerful network library with simplified and expressive syntax based on AFNetworking.

XMNetworking English Document XMNetworking 是一个轻量的、简单易用但功能强大的网络库,基于 AFNetworking 3.0+ 封装。 其中,XM 前缀是我们团队 Xcode-Men 的缩写。 简介 如上图所示,XMNetworking 采用中心化的设计思想

KANGZUBIN 981 Dec 29, 2022
An easy to integrate Model Based Google Maps Helper (SVHTTPClient, AFNetworking) That lets you Geo Code , Reverse Geocode, Get Directions , Places Autocomplete.

GoogleMapsHelper Read Me in Russian : http://gargo.of.by/googlemapshelper/ A GOOGLE MAPS Helper that help you do multiple tasks like HOW TO USE // usi

Zeeshan Haider 21 Jul 28, 2022
Permission Util for iOS (feat.RxSwift)

EzRxPermission Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation EzR

Yunjae-Na 4 Jun 30, 2022
The perfect accessory for Mantle and AFNetworking.

Overcoat We are finding maintainers, contact @sodastsai :) Overcoat is a small but powerful library that makes creating REST clients simple and fun. I

null 1.1k Dec 2, 2022
A custom wrapper over AFNetworking library that we use inside RC extensively

AFNetworkingHelper A very simple wrapper over the most amazing networking library for objective C, AFNetworking. We extensively use it inside RC and i

Betacraft 16 Aug 3, 2021
Synchronous requests for AFNetworking 1.x, 2.x, and 3.x

AFNetworking-Synchronous A minimal category which extends AFNetworking to support synchronous requests. Usage 3.x pod 'AFNetworking', '~> 3.0' pod

Paul Melnikow 160 Dec 7, 2022
Postie - The Next-Level HTTP API Client using Combine

Postie - The Next-Level HTTP API Client using Combine Postie is a pure Swift library for building URLRequests using property wrappers.

kula 28 Jul 23, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

Angel Rada 19 Sep 8, 2022
Minimalistic Swift HTTP request agent for iOS and OS X

Agent Table of Contents Introduction Usage HTTP Verbs Overloading Method Chaining Response Closure Verbs Methods NSMutableURLRequest Contributing Lice

null 589 Jun 29, 2022
Automatically sets the network activity indicator for any performed request.

BigBrother BIG BROTHER IS WATCHING YOU. BigBrother is a Swift library made for iOS that automatically watches for any performed request and sets the n

Marcelo Fabri 446 Dec 17, 2022
Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

Le Van Nghia 304 Jun 29, 2022
An Generic HTTP Request Library For Swift

GRequest An HTTP request library written in Swift. ##Basic Usage Be simple, as it should be: Request("https://api.github.com/repos/lingoer/SwiftyJSON/

Ruoyu Fu 114 Oct 18, 2022
NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. ⚙️🚀

SONetworking NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. Project Folder and File Struc

Ahmad AlSofi 4 Jan 28, 2022
DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features ?? Typed network resources ?? Value oriented architecture ?? Exchangeable implementations ?? Extendable API ?? Composable

DB Systel GmbH 33 Jan 10, 2022
An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

null 10 Nov 20, 2022
Request adapter for URL requests from "MovieLister" demo app (Swift for Good book, a chapter by Ben Scheirman)

RequestAdapter Request adapter for URL requests from "MovieLister" demo app (Swift for Good book, a chapter by Ben Scheirman) The code is taken from:

Mihaela Mihaljevic Jakic 0 Nov 22, 2021
Minimalist HTTP request library via async / await

Making HTTP API requests in Swift using Foundation can be verbose and use a mix of types like URL, URLComponents and URLRequest to form a request and then handling all the encoding and decoding steps later

Nicholas Maccharoli 13 Nov 5, 2022
iONess is HTTP Request Helper for iOS platform used by HCI iOS App

iONess iONess (iOS Network Session) is HTTP Request Helper for the iOS platform used by Home Credit Indonesia iOS App. It uses Ergo as a concurrent he

OSFE Homecredit Indonesia 1 Mar 28, 2022