在一个照片分享应用中用到AFHttpClient类。我要保存ios keychain 的访问令牌,因此不需要在每一个应用启动验证。但是我目前只能在登录一次之后进行验证和保存访问令牌。
#define kAccessTokenInstagram @"Token"
#define INSTAGRAM_AUTH_URL_FORMAT @"https://instagram.com/oauth/authorize/?client_id=%@&redirect_uri=%@&response_type=token"
#import "InstagramClient.h"
#import "Lockbox.h"
@interface InstagramClient ()
@property (nonatomic, copy) NSString *accessToken;
@end
@implementation InstagramClient
+ (instancetype)sharedClient {
static InstagramClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseURL = [NSURL URLWithString:@"https://api.instagram.com/v1/"];
_sharedClient = [[InstagramClient alloc] initWithBaseURL:baseURL];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (self) {
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
}
return self;
}
- (void)authenticateWithClientID:(NSString *)clientId callbackURL:(NSString *)callbackUrl {
NSString *urlString = [NSString stringWithFormat:INSTAGRAM_AUTH_URL_FORMAT, clientId, callbackUrl];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
}
- (void)handleOAuthCallbackWithURL:(NSURL *)url {
NSError *regexError = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[^#]*#access_token=(.*)$"
options:0
error:®exError];
NSString *input = [url description];
[regex enumerateMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
if ([result numberOfRanges] > 1) {
NSRange accessTokenRange = [result rangeAtIndex:1];
self.accessToken = [input substringWithRange:accessTokenRange];
NSLog(@"Access Token: %@", self.accessToken);
NSString *token = self.accessToken;
[Lockbox setString:token forKey:kAccessTokenInstagram];
}
}];
}
- (NSString *)accessToken {
return [Lockbox stringForKey:kAccessTokenInstagram];
}
-(AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure {
NSMutableURLRequest *request = [urlRequest mutableCopy];
NSString *separator = [request.URL query] ? @"&" : @"?";
NSString *newURLString = [NSString stringWithFormat:@"%@%@access_token=%@", [request.URL absoluteString], separator, self.accessToken];
NSURL *newURL = [[NSURL alloc] initWithString:newURLString];
[request setURL:newURL];
return [super HTTPRequestOperationWithRequest:request success:success failure:failure];
}
@end
这是出问题的代码:
- (NSString *)accessToken {
return [Lockbox stringForKey:kAccessTokenInstagram];
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。