1.统一设置网络请求的服务器和 CDN 的地址
YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];
config.baseUrl = @"http://yuantiku.com";
config.cdnUrl = @"http://fen.bi";
2.YTKRequest类 覆盖以下方法
//拼接表示详细的url
- (NSString *)requestUrl {
// “http://www.yuantiku.com” 在 YTKNetworkConfig 中设置,这里只填除去域名剩余的网址信息
return @"/iphone/register";
}
// 请求类型
- (YTKRequestMethod)requestMethod {
return YTKRequestMethodPost;
}
//post请求体
- (id)requestArgument {
return @{
@"username": _username,
@"password": _password
};
}
//验证返回数据
- (id)jsonValidator {
return @{
@"nick": [NSString class],
@"level": [NSNumber class]
};
}
//设置一个3分钟的缓存,3分钟内调用调Api的start方法,实际上并不会发送真正的请求。
- (NSInteger)cacheTimeInSeconds {
// cache 3 minutes, which is 60 * 3 = 180 seconds
return 60 * 3;
}
//使用useCDN 地址请求
- (BOOL)useCDN {
return YES;
}
//上传文件 我们可以通过覆盖 constructingBodyBlock 方法,来方便地上传图片等附件,如下是一个示例:
- (AFConstructingBlock)constructingBodyBlock {
return ^(id<AFMultipartFormData> formData) {
NSData *data = UIImageJPEGRepresentation(_image, 0.9);
NSString *name = @"image";
NSString *formKey = @"image";
NSString *type = @"image/jpeg";
[formData appendPartWithFileData:data name:formKey fileName:name mimeType:type];
};
}
- (id)jsonValidator {
return @{ @"imageId": [NSString class] };
}
- (NSString *)responseImageId {
NSDictionary *dict = self.responseJSONObject;
return dict[@"imageId"];
}
//重写 若这个方法返回非nil对象,会忽略requestUrl, requestArgument, requestMethod,requestSerializerType,requestHeaderFieldValueDictionary
- (NSURLRequest *)buildCustomUrlRequest {
NSData *rawData = [[_events jsonString] dataUsingEncoding:NSUTF8StringEncoding];
NSData *gzippingData = [NSData gtm_dataByGzippingData:rawData];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.requestUrl]];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
[request setHTTPBody:gzippingData];
}
//设置请求头
- (NSDictionary<NSString *,NSString *> *)requestHeaderFieldValueDictionary {
//设置通用header 签名
return @{@"":@""};
}
3.其他类
/*请求多个类
YTKBatchRequest
*/
/*依赖请求
YTKChainRequest
*/
4.调用
//具体的方法是直接使用 YTKRequest 的 - (BOOL)loadCacheWithError: 方法,即可获得上次缓存的内容。当然,你需要把 - (NSInteger)cacheTimeInSeconds 覆盖,返回一个大于等于 0 的值,这样才能开启 YTKRequest 的缓存功能,否则默认情况下,缓存功能是关闭的。
NSString *userId = @"1";
GetUserInfoApi *api = [[GetUserInfoApi alloc] initWithUserId:userId];
if ([api loadCacheWithError:nil]) {
NSDictionary *json = [api responseJSONObject];
NSLog(@"json = %@", json);
// show cached data
}
[api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
NSLog(@"update ui");
} failure:^(YTKBaseRequest *request) {
NSLog(@"failed");
}];
5.other
Override
- (NSInteger)cacheTimeInSeconds; //当前请求指定时间内,使用缓存数据
- (long long)cacheVersion; //当前请求,指定使用版本号的缓存数据