我怎么能通过我社交网站集成到iPhone应用程序

时间:2013-06-11 15:22:22

标签: xcode ios6 oauth social-networking

嗨我想将 Via Me 社交网站整合到我的iphone应用程序中,我用谷歌搜索但没有找到任何样本。

1 个答案:

答案 0 :(得分:1)

基本流程如下:

  1. 为您的应用创建custom URL scheme。 Via Me将在用户通过身份验证后使用此功能,以返回到您的应用。在我的示例中,我创建了一个名为" robviame://"

  2. http://via.me/developers注册您的应用。这将为您提供客户端ID和客户端密码:

    register app at via.me

  3. 如果要对用户进行身份验证,请致电:

    NSString *redirectUri = [[self redirectURI] stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding];
    NSString *urlString = [NSString stringWithFormat:@"https://api.via.me/oauth/authorize/?client_id=%@&redirect_uri=%@&response_type=code", kClientID, redirectUri];
    NSURL *url = [NSURL URLWithString:urlString];
    [[UIApplication sharedApplication] openURL:url];
    
  4. 这样做会启动您的网络浏览器,并让用户有机会登录并授予您应用的权限。当用户完成该过程时,由于您已经定义了自定义网址方案,因此会在您的应用委托中调用以下方法:

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        // do whatever you want here to parse the code provided back to the app
    }
    
    例如,我将为我的Via Me响应调用处理程序:

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        ViaMeManager *viaMeManager = [ViaMeManager sharedManager];
    
        if ([[url host] isEqualToString:viaMeManager.host])
        {
            [viaMeManager handleViaMeResponse:[self parseQueryString:[url query]]];
    
            return YES;
        }
    
        return NO;
    }
    
    // convert the query string into a dictionary
    
    - (NSDictionary *)parseQueryString:(NSString *)query
    {
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        NSArray *queryParameters = [query componentsSeparatedByString:@"&"];
    
        for (NSString *queryParameter in queryParameters) {
            NSArray *elements = [queryParameter componentsSeparatedByString:@"="];
            NSString *key     = [elements[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *value   = [elements[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            value             = [[value componentsSeparatedByString:@"+"] componentsJoinedByString:@" "];
    
            [dictionary setObject:value forKey:key];
        }
        return dictionary;
    }
    
    例如,该处理程序可能会保存代码,然后请求访问令牌:

    - (void)handleViaMeResponse:(NSDictionary *)parameters
    {
        self.code = parameters[@"code"];
    
        if (self.code)
        {
            // save the code
    
            [[NSUserDefaults standardUserDefaults] setValue:self.code forKey:kViaMeUserDefaultKeyCode];
            [[NSUserDefaults standardUserDefaults] synchronize];
    
            // now let's authenticate the user and get an access key
    
            [self requestToken];
        }
        else
        {
            NSLog(@"%s: parameters = %@", __FUNCTION__, parameters);
    
            NSString *errorCode = parameters[@"error"];
            if ([errorCode isEqualToString:@"access_denied"])
            {
                [[[UIAlertView alloc] initWithTitle:nil
                                            message:@"Via Me functions will not be enabled because you did not authorize this app"
                                           delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil] show];
            }
            else
            {
                [[[UIAlertView alloc] initWithTitle:nil
                                            message:@"Unknown Via Me authorization error"
                                           delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil] show];
            }
        }
    }
    

    并且检索令牌的代码可能如下所示:

    - (void)requestToken
    {
        NSURL *url = [NSURL URLWithString:@"https://api.via.me/oauth/access_token"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
    
        NSDictionary *paramsDictionary = @{@"client_id"     : kClientID,
                                           @"client_secret" : kClientSecret,
                                           @"grant_type"    : @"authorization_code",
                                           @"redirect_uri"  : [self redirectURI],
                                           @"code"          : self.code,
                                           @"response_type" : @"token"
                                           };
    
        NSMutableArray *paramsArray = [NSMutableArray array];
        [paramsDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
            [paramsArray addObject:[NSString stringWithFormat:@"%@=%@", key, [obj stringByAddingPercentEscapesForURLParameterUsingEncoding:NSUTF8StringEncoding]]];
        }];
    
        NSData *paramsData = [[paramsArray componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:paramsData];
    
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            if (error)
            {
                NSLog(@"%s: NSURLConnection error = %@", __FUNCTION__, error);
                return;
            }
    
            NSError *parseError;
            id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    
            if (parseError)
            {
                NSLog(@"%s: NSJSONSerialization error = %@", __FUNCTION__, parseError);
                return;
            }
    
            self.accessToken = results[@"access_token"];
    
            if (self.accessToken)
            {
                [[NSUserDefaults standardUserDefaults] setValue:self.accessToken forKey:kViaMeUserDefaultKeyAccessToken];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }];
    }
    
  5. 希望这足以让你前进。这在http://via.me/developers页面中有更详细的描述。