现在,在我的代码中,我有很多代码块的重复:
NSString *imageID = [postURL.path substringFromIndex:1];
NSString *APILink = [NSString stringWithFormat:@"https://api.imgur.com/3/image/%@", imageID];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager.requestSerializer setValue:@"Client-ID --myID--" forHTTPHeaderField:@"Authorization"];
[operationManager GET:APILink
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
有没有办法将其简化为更可重用的代码块?我记得在AFNetworking 1.0中继承AFHTTPClient
以完成类似的事情,但我对如何在AFNetworking 2.0中做到这一点感到困惑。
答案 0 :(得分:1)
您可以将代码放入AFHTTPRequestOperationManager
如果我的代码分析正确:
MyServicesAPIAddition.h
@interface AFHTTPRequestOperationManager(MyServicesAPIAddition)
+ (void)resourceWithURL:(NSURL*)URL clientID:(NSString *)clientID completionHandler:(void (^)(AFHTTPRequestOperation *operation, id responseObject))handler;
@end
MyServicesAPIAddition.m
@implementation AFHTTPRequestOperationManager(MyServicesAPIAddition)
+ (void)resourceWithURL:(NSURL*)URL clientID:(NSString *)clientID completionHandler:(void (^)(AFHTTPRequestOperation *operation, id responseObject))handler
{
NSString *imageID = [URL.path substringFromIndex:1];
NSString *APILink = [NSString stringWithFormat:@"https://api.imgur.com/3/image/%@", imageID];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager.requestSerializer setValue:[NSString stringWithFormat:@"Client-ID %@", clientID] forHTTPHeaderField:@"Authorization"];
[operationManager GET:APILink
parameters:nil
success:handler];
}
@end
然后:
[AFHTTPRequestOperationManager resourceWithURL:postURL clientID:… completionHandler:
^(AFHTTPRequestOperation *operation, id responseObject)
{
…
}
想要在方法名称中添加后缀以防止选择器冲突。我没有。