我正在编写一个社交网络应用程序,用户可以在其中关注其他用户及其事件。
在服务器端,每个用户都使用一个 token 进行标识,该 token 将在 60 分钟后过期。
如果 token 已过期,并且用户想要调用方法- (void) followUserWithID:(NSNumber *)targetUserID
,我希望此方法首先调用我的autologinMethod(以确保用户的 token 现在有效),然后重复 - (void) followUserWithID:(NSNumber *)targetUserID
注意:我不希望“checkValidToken”请求发起额外的 HTTP 请求。
-(void)commandWithParams:(NSMutableDictionary*)params command:(NSString *)command onCompletion:(JSONResponseBlock)completionBlock
{
NSString *_path = [NSString stringWithFormat:@"%@%@",self.baseURL, command];
NSLog(@"path: %@", _path );
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:@"POST"
path:_path
parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
NSLog(@"%@",responseObject);
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"ERROR"]);
// Unable to establish a connection to the server.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Server error"
message:@"Please try again later"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}];
[operation start];
}
- (void)followUserWithID:(NSNumber *)targetUserID
{
NSNumber *ownID = [[NSUserDefaults standardUserDefaults] objectForKey:@"id"];
NSMutableDictionary *HTTPPostDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
ownID, @"target_user_id",
targetUserID, @"user_id",nil];
[[WebAPI sharedInstance] commandWithParams:HTTPPostDictionary command:@"follow_user" onCompletion:^(NSDictionary *json){
NSLog(@"%@", json);
}];
}
最佳答案
你需要
- 检查 AFNetworking 完成 block 中的 token 是否有效
- 如果 token 已过期,请续订,然后重试该操作
根据您的服务器在这种情况下提供的 HTTP 状态代码,您的检查将位于 success
或 failure
block 中。
这是一个粗略的轮廓:
if (/* the token has expired */) {
AFHTTPRequestOperation *operationToRetryAfterTokenRenewal = [operation copy];
//TODO: set the completion blocks for operationToRetryAfterTokenRenewal.
[myTokenRenewer autologinMethodWithCompletionBlock:^{
[operationToRetryAfterTokenRenewal start];
}];
}
两个注意事项:
- 注意待办事项。当您复制
AFHTTPRequestOperation
对象时,完成 block 不会保留,因此您需要再次设置它们。 (有关详细信息,请参阅 AFURLConnectionOperation NSCopying Caveats。) - 您确实应该使用
[[myHTTPClient sharedClient] enqueueHTTPRequestOperation:operation]
而不是[operation start]
,特别是当您要进行文件上传时。这允许系统控制一次运行多少个操作,并在网络可达性暂时暂停时延迟运行它们。
关于iphone - iOS:AFNetworking:如果 token 过期则重复 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17189697/