RestKit ,如果是由于令牌过期引起的,则拦截失败的请求/重试
Posted
技术标签:
【中文标题】RestKit ,如果是由于令牌过期引起的,则拦截失败的请求/重试【英文标题】:RestKit , Intercept failed request/ retry if it was caused due to token Expiration 【发布时间】:2016-07-12 18:51:21 【问题描述】:我有一个名为 API 助手的类,其方法如下所示:
+(RKObjectManager*) getRestObjectManager
NSURL *baseURL = [NSURL URLWithString:BASE_URL];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
return objectManager;
我将创建 API_User 、 API_Group 等类。这些类中的每一个都有类似
的方法+(void)getDetails:(void (^)(User* user) )onSuccess
//fetch object manager from api helper and perform request, on success, call the onSuccess block from the function parameter.
onSuccess(user); //if it was successful, i will create a user object and //return.
将有几种方法,例如 getDetails ,每种方法都需要发送身份验证令牌才能工作。令牌可以过期,需要刷新。
我该怎么做:
在 API helper 中定义某种拦截器,这样当请求失败时,它会获取一个新令牌(我的令牌过期响应本身提供一个新令牌),然后重试失败的请求?我不想为我定义的每个端点处理这个。
【问题讨论】:
【参考方案1】:我所做的是扩展 RKObject Manager 并在那里处理故障,如下所示:
@implementation MYOWNObjectManager
#pragma mark - RKObjectManager Overrides
- (void)getObjectsAtPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(RKObjectRequestOperation *operation,
RKMappingResult *mappingResult))success failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure
[super getObjectsAtPath:path parameters:parameters success:success failure:^(RKObjectRequestOperation *operation, NSError *error)
//check if failure was due to token expiry, if yes call the code to refresh token. otherwise just call failure(operation, error);
[super getObjectsAtPath:path parameters:parameters success:success failure:failure]; //this line performs the request again.
];
此 sn-p 仅用于 GET。您还需要使用相同的逻辑覆盖 PUT/POST 等
【讨论】:
以上是关于RestKit ,如果是由于令牌过期引起的,则拦截失败的请求/重试的主要内容,如果未能解决你的问题,请参考以下文章