Ytk mining machine app
Publish: 2021-05-15 19:11:32
1. Ytkurlfilterprotocol
interface
ytkurlfilterprotocol interface is used to rewrite the URL or parameters of network request, such as adding some parameters to the network request or modifying some paths
for example, in the ape question bank, we need to add the version number of the client to each network request as a parameter. So we implement the following ytkurlargumentsfilter class, and implement the ytkurlfilterprotocol interface:
/ / ytkurlargumentsfilter. H
@ interface ytkurlargumentsfilter: nsobject & lt; YTKUrlFilterProtocol>< br />
+ (YTKUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments;< br />
- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request;< br />
@end
// YTKUrlArgumentsFilter.m
@implementation YTKUrlArgumentsFilter {
NSDictionary *_ arguments;< br />}
+ (YTKUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments {
return [[self alloc] initWithA rguments:arguments ];< br />}
- (id)initWithArguments:(NSDictionary *)arguments {
self = [super init];< br /> if (self) {
_ arguments = arguments;< br /> }
return self;< br />}
- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request {
return [YTKNetworkPrivate urlStringWithOriginUrlS tring:originUrl appendParameters :_ arguments];
}
@ end
through the above ytkurlargumentsfilter class, we can easily add unified parameters for network requests with the following code, For example, add the version number of the current client:
- (bool) application: (uiapplication *) application
didfinish launching with options: (nsdictionary *) launchoptions {
[self setup request filters]< br /> return YES;< br />}
- (void)setupRequestFilters {
NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@" CFBundleShortVersionString"];< br /> YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];< br /> YTKUrlArgumentsFilter *urlFilter = [YTKUrlArgumentsFilter filterWithArguments:@{@" version": appVersion}];< br /> [config addUrlF ilter:urlFilter ];<
}
ytkbatchrequest
class
ytkbatchrequest class: it is used to conveniently send batch network requests. Ytkbatchrequest is a container class, which can place multiple ytkbatchrequest subclasses and handle the success and failure of these multiple network requests in a unified way
in the following example, we send four batch requests and process the successful callbacks of the four requests< br />
#import " YTKBatchRequest.h"< br />#import " GetImageApi.h"< br />#import " GetUserInfoApi.h"< br />
- (void)sendBatchRequest {
GetImageApi *a = [[GetImageApi alloc] initWithImageId:@" 1.jpg"];< br /> GetImageApi *b = [[GetImageApi alloc] initWithImageId:@" 2.jpg"];< br /> GetImageApi *c = [[GetImageApi alloc] initWithImageId:@" 3.jpg"];< br /> GetUserInfoApi *d = [[GetUserInfoApi alloc] initWithUserId:@" 123"];< br /> YTKBatchRequest *batchRequest = [[YTKBatchRequest alloc] initWithRequestArray:@[a, b, c, d]];< br /> [batchRequest :^(YTKBatchRequest *batchRequest) {
NSLog(@" succeed");< br /> NSArray *requests = batchRequest.requestArray;< br /> GetImageApi *a = (GetImageApi *)requests[0];< br /> GetImageApi *b = (GetImageApi *)requests[1];< br /> GetImageApi *c = (GetImageApi *)requests[2];< br /> GetUserInfoApi *user = (GetUserInfoApi *)requests[3];< br /> // deal with requests result ...
} failure:^(YTKBatchRequest *batchRequest) {
NSLog(@" failed");< br /> }];<
}
ytkchainrequest
class
is used to manage interdependent network requests. In fact, it can be used to manage multiple network requests after topology sorting
for example, we have a requirement that when users register, they first send registered APIs, and then:
if the registration is successful, they send APIs to read the user information. Moreover, the API reading user information needs to use the user ID number returned after successful registration
if the registration fails, the API reading the user information will not be sent
the following is a specific code example. In the example, we set the API mutual dependencies in the sendchainrequest method, and then use the. We can use the chainrequestfinished callback to process the logic that all network requests are sent successfully. If any of the network requests fail, the chainrequestfailed callback is triggered< br />- (void)sendChainRequest {
RegisterApi *reg = [[RegisterApi alloc] initWithUsername:@" username" password:@" password"];< br /> YTKChainRequest *chainReq = [[YTKChainRequest alloc] init];< br /> [chainReq addR equest:reg callback :^(YTKChainRequest *chainRequest, YTKBaseRequest *baseRequest) {
RegisterApi *result = (RegisterApi *)baseRequest;< br /> NSString *userId = [result userId];< br /> GetUserInfoApi *api = [[GetUserInfoApi alloc] initWithUserId:userId];< br /> [chainRequest addR equest:api callback :nil];< br />
}];< br /> chainReq.delegate = self;< br /> // start to send request
[chainReq start];
}
- (void) chainrequest finished: (ytk chainrequest *) chainrequest {
/ / all requests are done
}
- (void) chainrequest failed: (ytk chainrequest *) chainrequest failed baserequest: (ytk baserequest *) request {
/ / some one of requests is failed
}
displays the contents of the last cache
when it is actually opened Some content may load very slowly. We want to display the last content first, and then replace the last content with the latest content after loading successfully. Sometimes, because the network is disconnected, we want to display the contents of the last cache for friendliness. At this time, you can use ytkreqeust's advanced usage of directly loading the cache
the specific method is to directly use the -
(ID) cachejson method of ytkrequest to obtain the last cached content. Of course, you need to override - (nsinteger) cachetimeinseconds and return a value greater than or equal to 0 to enable the caching function of ytkrequest. Otherwise, the caching function is turned off by default
the following is an example. Before loading user information, we first obtain the last loaded content, and then send a request. After the request is successful, we update the interface:
- (void) loadcachedata {
nsstring * userid = @ & quot; 1";< br /> GetUserInfoApi *api = [[GetUserInfoApi alloc] initWithUserId:userId];< br /> if ([api cacheJson]) {
NSDictionary *json = [api cacheJson];< br /> NSLog(@" json = %@", json);< br /> // show cached data
}
[api :^(YTKBaseRequest *request) {
NSLog(@" update ui");< br /> } failure:^(YTKBaseRequest *request) {
NSLog(@" failed");< br /> }];<
}
upload files
we can easily upload pictures and other attachments by overriding the constructingbodyblock method. Here is an example:
/ / ytkrequest. H
? Import & quot; YTKRequest.h"< br />
@interface UploadImageApi : YTKRequest
- (id)initWithImage:(UIImage *)image;< br />- (NSString *)responseImageId;< br />
@end
// YTKRequest.m
@implementation UploadImageApi {
UIImage *_ image;< br />}
- (id)initWithImage:(UIImage *)image {
self = [super init];< br /> if (self) {
_ image = image;< br /> }
return self;< br />}
- (YTKRequestMethod)requestMethod {
return YTKRequestMethodPost;< br />}
- (NSString *)requestUrl {
return @"/ iphone/image/upload";< br />}
- (AFConstructingBlock)constructingBodyBlock {
return ^(id< AFMultipartFormData> formData) {
NSData *data = UIImageJPEGRepresentation(_ image, 0.9);< br /> NSString *name = @" image";< br /> NSString *formKey = @" image";< br /> NSString *type = @" image/jpeg";< br /> [formData appendPartWithFileD ata:data name :formKey fileN ame:name mimeType :type];< br /> };< br />}
- (id)jsonValidator {
return @{ @" imageId": [ NSString class] };< br />}
- (NSString *)responseImageId {
NSDictionary *dict = self.responseJSONObject;< br /> return dict[@" imageId"];
}
@ end
through the above code, we create an upload image, and then obtain the network request API of ImageID returned by the server<
customize the headerfield of the network request
return a dictionary object through the overlay method to customize the headerfield of the request. For the returned dictionary, the key is the key of the headerfield and the value is the value of the headerfield. It should be noted that both the key and the value must be string objects
Customize buildcustomurlrequest
by overriding the buildcustomurlrequest method and returning an nsurlrequest object, the requirement of fully customized request can be achieved. This method is defined in the ytkbaserequest class, as follows:
/ / build a custom urlrequest,
/ / if this method returns a non nil object, it will ignore the requesturl, requestargument, requestmethod, requestserializertype,
- (nsurlrequest *) buildcustomurlrequest
as the comment says, if you build a custom request, you will ignore all other custom request methods, such as requesturl, requestargument, requestmethod, and requestserializertype,. An example of uploading gzippingdata is as follows:
- (nsurlrequest *) buildcustomurlrequest {
nsdata * rawdata =[[_ events jsonString] dataUsingE ncoding:NSUTF8StringEncoding ];< br /> NSData *gzippingData = [NSData gtm_ dataByGzippingD ata:rawData ];< br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithS tring:self.requestUrl ]];< br /> [request setHTTPMethod:@" POST"];< br /> [request addValue:@" application/json; charset=UTF-8" forHTTPHeaderField:@" Content-Type"];< br /> [request addValue:@" gzip" forHTTPHeaderField:@" Content-Encoding"];< br /> [request setHTTPB ody:gzippingData ];< br /> return request;< br />}
interface
ytkurlfilterprotocol interface is used to rewrite the URL or parameters of network request, such as adding some parameters to the network request or modifying some paths
for example, in the ape question bank, we need to add the version number of the client to each network request as a parameter. So we implement the following ytkurlargumentsfilter class, and implement the ytkurlfilterprotocol interface:
/ / ytkurlargumentsfilter. H
@ interface ytkurlargumentsfilter: nsobject & lt; YTKUrlFilterProtocol>< br />
+ (YTKUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments;< br />
- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request;< br />
@end
// YTKUrlArgumentsFilter.m
@implementation YTKUrlArgumentsFilter {
NSDictionary *_ arguments;< br />}
+ (YTKUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments {
return [[self alloc] initWithA rguments:arguments ];< br />}
- (id)initWithArguments:(NSDictionary *)arguments {
self = [super init];< br /> if (self) {
_ arguments = arguments;< br /> }
return self;< br />}
- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request {
return [YTKNetworkPrivate urlStringWithOriginUrlS tring:originUrl appendParameters :_ arguments];
}
@ end
through the above ytkurlargumentsfilter class, we can easily add unified parameters for network requests with the following code, For example, add the version number of the current client:
- (bool) application: (uiapplication *) application
didfinish launching with options: (nsdictionary *) launchoptions {
[self setup request filters]< br /> return YES;< br />}
- (void)setupRequestFilters {
NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@" CFBundleShortVersionString"];< br /> YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];< br /> YTKUrlArgumentsFilter *urlFilter = [YTKUrlArgumentsFilter filterWithArguments:@{@" version": appVersion}];< br /> [config addUrlF ilter:urlFilter ];<
}
ytkbatchrequest
class
ytkbatchrequest class: it is used to conveniently send batch network requests. Ytkbatchrequest is a container class, which can place multiple ytkbatchrequest subclasses and handle the success and failure of these multiple network requests in a unified way
in the following example, we send four batch requests and process the successful callbacks of the four requests< br />
#import " YTKBatchRequest.h"< br />#import " GetImageApi.h"< br />#import " GetUserInfoApi.h"< br />
- (void)sendBatchRequest {
GetImageApi *a = [[GetImageApi alloc] initWithImageId:@" 1.jpg"];< br /> GetImageApi *b = [[GetImageApi alloc] initWithImageId:@" 2.jpg"];< br /> GetImageApi *c = [[GetImageApi alloc] initWithImageId:@" 3.jpg"];< br /> GetUserInfoApi *d = [[GetUserInfoApi alloc] initWithUserId:@" 123"];< br /> YTKBatchRequest *batchRequest = [[YTKBatchRequest alloc] initWithRequestArray:@[a, b, c, d]];< br /> [batchRequest :^(YTKBatchRequest *batchRequest) {
NSLog(@" succeed");< br /> NSArray *requests = batchRequest.requestArray;< br /> GetImageApi *a = (GetImageApi *)requests[0];< br /> GetImageApi *b = (GetImageApi *)requests[1];< br /> GetImageApi *c = (GetImageApi *)requests[2];< br /> GetUserInfoApi *user = (GetUserInfoApi *)requests[3];< br /> // deal with requests result ...
} failure:^(YTKBatchRequest *batchRequest) {
NSLog(@" failed");< br /> }];<
}
ytkchainrequest
class
is used to manage interdependent network requests. In fact, it can be used to manage multiple network requests after topology sorting
for example, we have a requirement that when users register, they first send registered APIs, and then:
if the registration is successful, they send APIs to read the user information. Moreover, the API reading user information needs to use the user ID number returned after successful registration
if the registration fails, the API reading the user information will not be sent
the following is a specific code example. In the example, we set the API mutual dependencies in the sendchainrequest method, and then use the. We can use the chainrequestfinished callback to process the logic that all network requests are sent successfully. If any of the network requests fail, the chainrequestfailed callback is triggered< br />- (void)sendChainRequest {
RegisterApi *reg = [[RegisterApi alloc] initWithUsername:@" username" password:@" password"];< br /> YTKChainRequest *chainReq = [[YTKChainRequest alloc] init];< br /> [chainReq addR equest:reg callback :^(YTKChainRequest *chainRequest, YTKBaseRequest *baseRequest) {
RegisterApi *result = (RegisterApi *)baseRequest;< br /> NSString *userId = [result userId];< br /> GetUserInfoApi *api = [[GetUserInfoApi alloc] initWithUserId:userId];< br /> [chainRequest addR equest:api callback :nil];< br />
}];< br /> chainReq.delegate = self;< br /> // start to send request
[chainReq start];
}
- (void) chainrequest finished: (ytk chainrequest *) chainrequest {
/ / all requests are done
}
- (void) chainrequest failed: (ytk chainrequest *) chainrequest failed baserequest: (ytk baserequest *) request {
/ / some one of requests is failed
}
displays the contents of the last cache
when it is actually opened Some content may load very slowly. We want to display the last content first, and then replace the last content with the latest content after loading successfully. Sometimes, because the network is disconnected, we want to display the contents of the last cache for friendliness. At this time, you can use ytkreqeust's advanced usage of directly loading the cache
the specific method is to directly use the -
(ID) cachejson method of ytkrequest to obtain the last cached content. Of course, you need to override - (nsinteger) cachetimeinseconds and return a value greater than or equal to 0 to enable the caching function of ytkrequest. Otherwise, the caching function is turned off by default
the following is an example. Before loading user information, we first obtain the last loaded content, and then send a request. After the request is successful, we update the interface:
- (void) loadcachedata {
nsstring * userid = @ & quot; 1";< br /> GetUserInfoApi *api = [[GetUserInfoApi alloc] initWithUserId:userId];< br /> if ([api cacheJson]) {
NSDictionary *json = [api cacheJson];< br /> NSLog(@" json = %@", json);< br /> // show cached data
}
[api :^(YTKBaseRequest *request) {
NSLog(@" update ui");< br /> } failure:^(YTKBaseRequest *request) {
NSLog(@" failed");< br /> }];<
}
upload files
we can easily upload pictures and other attachments by overriding the constructingbodyblock method. Here is an example:
/ / ytkrequest. H
? Import & quot; YTKRequest.h"< br />
@interface UploadImageApi : YTKRequest
- (id)initWithImage:(UIImage *)image;< br />- (NSString *)responseImageId;< br />
@end
// YTKRequest.m
@implementation UploadImageApi {
UIImage *_ image;< br />}
- (id)initWithImage:(UIImage *)image {
self = [super init];< br /> if (self) {
_ image = image;< br /> }
return self;< br />}
- (YTKRequestMethod)requestMethod {
return YTKRequestMethodPost;< br />}
- (NSString *)requestUrl {
return @"/ iphone/image/upload";< br />}
- (AFConstructingBlock)constructingBodyBlock {
return ^(id< AFMultipartFormData> formData) {
NSData *data = UIImageJPEGRepresentation(_ image, 0.9);< br /> NSString *name = @" image";< br /> NSString *formKey = @" image";< br /> NSString *type = @" image/jpeg";< br /> [formData appendPartWithFileD ata:data name :formKey fileN ame:name mimeType :type];< br /> };< br />}
- (id)jsonValidator {
return @{ @" imageId": [ NSString class] };< br />}
- (NSString *)responseImageId {
NSDictionary *dict = self.responseJSONObject;< br /> return dict[@" imageId"];
}
@ end
through the above code, we create an upload image, and then obtain the network request API of ImageID returned by the server<
customize the headerfield of the network request
return a dictionary object through the overlay method to customize the headerfield of the request. For the returned dictionary, the key is the key of the headerfield and the value is the value of the headerfield. It should be noted that both the key and the value must be string objects
Customize buildcustomurlrequest
by overriding the buildcustomurlrequest method and returning an nsurlrequest object, the requirement of fully customized request can be achieved. This method is defined in the ytkbaserequest class, as follows:
/ / build a custom urlrequest,
/ / if this method returns a non nil object, it will ignore the requesturl, requestargument, requestmethod, requestserializertype,
- (nsurlrequest *) buildcustomurlrequest
as the comment says, if you build a custom request, you will ignore all other custom request methods, such as requesturl, requestargument, requestmethod, and requestserializertype,. An example of uploading gzippingdata is as follows:
- (nsurlrequest *) buildcustomurlrequest {
nsdata * rawdata =[[_ events jsonString] dataUsingE ncoding:NSUTF8StringEncoding ];< br /> NSData *gzippingData = [NSData gtm_ dataByGzippingD ata:rawData ];< br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithS tring:self.requestUrl ]];< br /> [request setHTTPMethod:@" POST"];< br /> [request addValue:@" application/json; charset=UTF-8" forHTTPHeaderField:@" Content-Type"];< br /> [request addValue:@" gzip" forHTTPHeaderField:@" Content-Encoding"];< br /> [request setHTTPB ody:gzippingData ];< br /> return request;< br />}
Hot content