ios - 尝试清理 iOS OAuth 代码

标签 ios networking oauth objective-c-blocks flickr

我在我的应用程序中添加了将图片上传到 Flickr 的功能。我正在使用 ObjectiveFlickr 并使用 SnapAndRun 示例代码,并使其正常工作。唯一的问题是,它看起来太丑了。

我很少编写太多网络编码,所以这有点难以理解。

使用 OAuth 授权我的应用程序似乎是通过许多函数来进行的……必须有一种更简洁的方法。

我考虑过使用 block ,但我没有很好地处理它。

我基本上有一个 5 步过程,从一个函数开始,将一些东西发送到 Flickr,Flickr 在另一个函数中返回并调用另一个函数,等等......请求 token ......等待回复,将进行 WebView 确认...获取另一个 token ...更多等待...最后点击我的上传代码。

有没有人用更干净的方式做到这一点?我想要一些指导。

非常感谢。

最佳答案

我在使用 tumblr 进行身份验证时遇到同样的问题。我找到了使用 oauth-consumer 的解决方案。您可以从git下载。或 google-group .

你必须在here中注册flicker api你可以从那里得到 CONSUMER_KEYCONSUMER_SECRET

#define CONSUMER_KEY @"your consumer key here"
#define CONSUMER_SECRET @"your secret key here"
#define authorize_url  @"http://www.flickr.com/services/oauth/authorize"
#define request_token_url  @"http://www.flickr.com/services/oauth/request_token"

-(void)btnPressed:(id)sender{
    self.consumer = [[OAConsumer alloc] initWithKey:CONSUMER_KEY secret:CONSUMER_SECRET];

    NSURL *url = [NSURL URLWithString:request_token_url];


    OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
                                                                   consumer:self.consumer
                                                                      token:nil   // we don't have a Token yet
                                                                      realm:nil   // our service provider doesn't specify a realm
                                                          signatureProvider:nil]; // use the default method, HMAC-SHA1

    [request setHTTPMethod:@"POST"];

    OADataFetcher *fetcher = [[OADataFetcher alloc] init];

    [fetcher fetchDataWithRequest:request
                         delegate:self
                didFinishSelector:@selector(requestTokenTicket:didFinishWithData:)
                  didFailSelector:@selector(requestTokenTicket:didFailWithError:)];
}

- (void)requestTokenTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
    if (ticket.didSucceed)
    {
        NSString *responseBody = [[NSString alloc] initWithData:data
                                                       encoding:NSUTF8StringEncoding];
        self.accessToken= [[OAToken alloc] initWithHTTPResponseBody:responseBody];

        NSURL *author_url = [NSURL URLWithString:[ NSString stringWithFormat:authorize_url,self.accessToken.key]];
        OAMutableURLRequest  *oaR = [[OAMutableURLRequest alloc] initWithURL:author_url consumer:nil token:nil realm:nil signatureProvider:nil];
        UIWebView  *webView =[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [[[UIApplication sharedApplication] keyWindow] addSubview:webView];
        webView.delegate=self;
        [webView setScalesPageToFit:YES];
        [webView loadRequest:oaR];

    }
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    NSString *url = [[request URL] absoluteString];
    NSString *keyOne = @"oauth_token";
    NSString *keyTwo = @"oauth_verifier";
    NSRange r1 =[url rangeOfString:keyOne];
    NSRange r2 =[url rangeOfString:keyTwo];
    if (r1.location!=NSNotFound && r2.location!=NSNotFound) {
        // Extract oauth_verifier from URL query
        NSString* verifier = nil;
        NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:@"&"];
        for (NSString* param in urlParams) {
            NSArray* keyValue = [param componentsSeparatedByString:@"="];
            NSString* key = [keyValue objectAtIndex:0];
            if ([key isEqualToString:@"oauth_verifier"]) {
                verifier = [keyValue objectAtIndex:1];
                break;
            }
        }
        if (verifier) {
            NSURL* accessTokenUrl = [NSURL URLWithString:@"http://www.tumblr.com/oauth/access_token"];
            OAMutableURLRequest* accessTokenRequest =[[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
                                                                                     consumer:self.consumer
                                                                                        token:self.accessToken
                                                                                        realm:nil
                                                                            signatureProvider:nil];
            OARequestParameter* verifierParam =[[OARequestParameter alloc] initWithName:@"oauth_verifier" value:verifier];
            [accessTokenRequest setHTTPMethod:@"POST"];
            [accessTokenRequest setParameters:[NSArray arrayWithObjects:verifierParam,nil]];
            OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
            [dataFetcher fetchDataWithRequest:accessTokenRequest
                                     delegate:self
                            didFinishSelector:@selector(requestTokenTicketForAuthorization:didFinishWithData:)
                              didFailSelector:@selector(requestTokenTicket:didFailWithError:)];
        } else {
            // ERROR!
        }
        [webView removeFromSuperview];
        return NO;
    }
    if([url isEqualToString:@"http://www.elegantmedia.com.au/"]){
        [webView removeFromSuperview];
        return NO;
    }
    return YES;
}


- (void)requestTokenTicketForAuthorization:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data
{
    if (ticket.didSucceed)
    {
        NSString *responseBody = [[NSString alloc] initWithData:data
                                                       encoding:NSUTF8StringEncoding];
        self.accessToken = [self.accessToken initWithHTTPResponseBody:responseBody];
        accessTokenKey=self.accessToken.key;
        accessTokenSecret=self.accessToken.secret;
        //[self post];

        NSString *blogUrl=(NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"tumblrBlogUrl"];
        if([blogUrl isEqualToString:@""]||blogUrl==nil){
            [self getUserInfo];
        }
        else{
            NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"picture" ofType:@"jpg"]];
            [self postPhoto:data caption:@"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when" inBlog:blogUrl];
        }
    }
    else
    {
        NSString *responseBody = [[NSString alloc] initWithData:data
                                                       encoding:NSUTF8StringEncoding];
        NSLog(@"Response = %@",responseBody);
    }


}
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error
{
    NSLog(@"Error = %@",[error localizedDescription]);
}

如果它需要任何其他参数,您可以从 here 获得.

关于ios - 尝试清理 iOS OAuth 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15130061/

相关文章:

iphone - iOS : date problem

iphone - 限制 UITextView 中的光标移动

php - 如何在 PHP 中为 $_SESSION 设置唯一名称?

delphi - 如何使用 Delphi 5 快速检查网络位置是否存在?

javascript - Withings API 不适用于 node-oauth

ios - iOS 中弹出窗口的黑色透明背景

ios - 为 Unwind Segue 更新变量 (Swift)

networking - Vagrant 无法转发此 VM 上的指定端口

twitter - 使用 Twitter 获取不记名 token

javascript - 使用 Oauth-JS 获取 YouTube channel 名称和链接