我正在编写一个Abstract类来从多个社交网络中获取数据。在考虑了我需要在这个类中使用的所有东西之后,在该类的其他子类中使用它我会开始编写一个简单的auth_token fetcher来获取facebook的授权以从页面获取所有状态更新轮廓。我没有看到什么是使代码工作的最佳方法:
+ (NSString *)requestAuthToken {
NSString *authTokenKey = [[self socialNetworkName] stringByAppendingString:@"AuthToken"];
NSString *authTokenDateKey = [[self socialNetworkName] stringByAppendingString:@"AuthTokenDate"];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
__block NSString *authToken = [userDefaults stringForKey:authTokenKey];
NSDate *authTokenDate = (NSDate* )[userDefaults objectForKey:authTokenDateKey];
NSTimeInterval expirationDate = [authTokenDate timeIntervalSinceNow];
NSTimeInterval now = [[NSDate date] timeIntervalSinceNow];
NSTimeInterval dateDiff = expirationDate - now;
int diff = roundf(dateDiff / (60 * 60 * 24));
if (authToken == nil|| diff >= kMaxDaysExpiratonForAuthToken) {
DLog(@"AuthToken not Cached, requesting token with %@", [self socialNetworkName]);
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:[self socialNetworkAPIURL]]];
NSDictionary *parameters = [self socialNetworkAPIAuthTokenParameters];
[httpClient getPath:[self socialNetworkAPIAuthTokenURLPath] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
authToken = [NSString stringWithUTF8String:[responseObject bytes]];
[userDefaults setObject:[NSDate date] forKey:authTokenDateKey];
[userDefaults setObject:authToken forKey:authTokenKey];
// [userDefaults synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(@"error requesting the token %@", error);
}];
}
return authToken;
}
我总是得到回报;
答案 0 :(得分:4)
块以异步方式执行。因此,您应该在请求函数中传递类的对象。成功或失败时,block将使用该对象返回结果。
+ (NSString *)requestAuthToken:(id)objOfCallerClass {
....
if (authToken == nil|| diff >= kMaxDaysExpiratonForAuthToken) {
....
[objOfCallerClass accessToken: authToken];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[objOfCallerClass accessToken: nil];
}];
}
return authToken;
}