简体   繁体   中英

Waiting for block completion to return token nsstring

I am coding a Abstract class to fetch data from multiple social networks. After thinking all the stuff I would need to use in this class that would make sense to use it in other subclasses from that class I've started to write a simple auth_token fetcher to get authorization from facebook to get all the statuses updates from a page profile. I am failing to see what would be the best approach to make code work:

+ (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;
}

I am getting the return always nill;

Blocks are executed asynchronously. So, you should pass the object of the class in request function. On success or failure, block will return the result using that object.

    + (NSString *)requestAuthToken:(id)objOfCallerClass {
....    
        if (authToken == nil|| diff >= kMaxDaysExpiratonForAuthToken) {
....
[objOfCallerClass accessToken: authToken];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [objOfCallerClass accessToken: nil];
            }];
        }

        return authToken;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM