Facebook-ios-sdk со встроенным UIWebView - PullRequest
15 голосов
/ 27 декабря 2010

Я работаю с новым facebook-ios-sdk и успешно интегрировал API в свое родное приложение.Я могу аутентифицировать пользователя и правильно настроить разрешения, используя всплывающее диалоговое окно с классами ios-sdk.

Для части моего приложения мне нужно использовать соединение facebook в UIWebView, используя javascript иHTML для обработки данных в веб-просмотре.Учитывая, что пользователь уже вошел в систему и прошел проверку подлинности с помощью описанной выше процедуры, я бы предположил, что UIWebView поделится этими учетными данными или что, по крайней мере, будет какой-то способ передачи или назначения учетных данных веб-представлению.

К сожалению, я обнаружил этот более ранний пост, который, похоже, предполагает, что эта схема не совсем работает ( iOS - вход в систему в webView после входа в SDK ).Кто-нибудь еще сталкивался с этим и / или нашел обходной путь?Похоже, это будет довольно простой вариант использования, учитывая, что я не пытаюсь запустить мобильное сафари или что-то в этом роде - все это в одном и том же родном приложении.

Просто кажется, что должен быть какой-то видпростой трюк или настройки, которые я скучаю.Может быть, как-то установить куки в новом UIWebView?или как то так?

Ответы [ 3 ]

1 голос
/ 19 сентября 2013

- таким образом Facebook-ios-sdk

@ свойство (неатомное, сохранение) NSString * chk;

@end

@implementation SettingsViewController
@synthesize chk,viewFbLogin;
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell;
AppDelegate *appDelegate;
UIViewController *tweetComposer;
ACAccount *twitterAccount;
ACAccountStore *account;
ACAccountType *accountType;
NSArray *arrayOfAccounts ;
int arr_row_num;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
           }
    return self;
}


- (void)storeAccountWithAccessToken:(NSString *)token secret:(NSString *)secret
{
    //  Each account has a credential, which is comprised of a verified token and secret
    ACAccountCredential *credential =
    [[ACAccountCredential alloc] initWithOAuthToken:token tokenSecret:secret];

    //  Obtain the Twitter account type from the store
    accountType =
    [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    //  Create a new account of the intended type
    twitterAccount = [[ACAccount alloc] initWithAccountType:accountType];

    //  Attach the credential for this user
    twitterAccount.credential = credential;

    //  Finally, ask the account store instance to save the account
    //  Note: that the completion handler is not guaranteed to be executed
    //  on any thread, so care should be taken if you wish to update the UI, etc.
    [account saveAccount:twitterAccount withCompletionHandler:^(BOOL success, NSError *error) {
        if (success) {
            // we've stored the account!
            NSLog(@"the account was saved!");
        }
        else {
            //something went wrong, check value of error
            NSLog(@"the account was NOT saved");

            // see the note below regarding errors...
            //  this is only for demonstration purposes
            if ([[error domain] isEqualToString:ACErrorDomain]) {

                // The following error codes and descriptions are found in ACError.h
                switch ([error code]) {
                    case ACErrorAccountMissingRequiredProperty:
                        NSLog(@"Account wasn't saved because "
                              "it is missing a required property.");
                        break;
                    case ACErrorAccountAuthenticationFailed:
                        NSLog(@"Account wasn't saved because "
                              "authentication of the supplied "
                              "credential failed.");
                        break;
                    case ACErrorAccountTypeInvalid:
                        NSLog(@"Account wasn't saved because "
                              "the account type is invalid.");
                        break;
                    case ACErrorAccountAlreadyExists:
                        NSLog(@"Account wasn't added because "
                              "it already exists.");
                        break;
                    case ACErrorAccountNotFound:
                        NSLog(@"Account wasn't deleted because"
                              "it could not be found.");
                        break;
                    case ACErrorPermissionDenied:
                        NSLog(@"Permission Denied");
                        break;
                    case ACErrorUnknown:
                    default: // fall through for any unknown errors...
                        NSLog(@"An unknown error occurred.");
                        break;
                }
            } else {
                // handle other error domains and their associated response codes...
                NSLog(@"%@", [error localizedDescription]);
            }
        }
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    account = [[ACAccountStore alloc] init];
    accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    arrayOfAccounts = [account accountsWithAccountType:accountType]; 
   // [self storeAccountWithAccessToken:@"119745010-g6YqvIdpyvBvYuaweR5oI1V1h9ugIqlj0toetlqg" secret:@"ysBO2E6dgOWj2vKEFoC3PCEypMaPrpycy5WIeodUNro"];



    appDelegate= (AppDelegate *)[[UIApplication sharedApplication] delegate];
    chk=appDelegate.chk_login;

    if (!appDelegate.session.isOpen) {
        // create a fresh session object
        appDelegate.session = [[FBSession alloc] init];
        if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
            // even though we had a cached token, we need to login to make the session usable
            [appDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                             FBSessionState status,
                                                             NSError *error) {
                // we recurse here, in order to update buttons and labels

            }];
        }
    }


    if ([chk isEqualToString:@"YES"] && (appDelegate.setting_flag==FALSE))
    {

        appDelegate.arr=[NSMutableArray arrayWithObjects:@"Change Password",@"Facebook Login",@"Twitter Login",nil];

    }

    else

    {
        if(appDelegate.setting_flag==FALSE) 
        appDelegate.arr=[NSMutableArray arrayWithObjects:@"Facebook Login",@"Twitter Login",nil];
    }



}


-(void) updateView
{



}
- (void)viewWillAppear:(BOOL)animated
{



}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [appDelegate.arr count];
}


- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{



  cell = [self.SettingsTable dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];




    if([[appDelegate.arr objectAtIndex:indexPath.row] isEqualToString:@"Twitter Login"])
    {




        twitterAccount = [arrayOfAccounts objectAtIndex:0];
        NSLog(@"array=%@",[arrayOfAccounts objectAtIndex:0]);
        NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary:
                                  [twitterAccount dictionaryWithValuesForKeys:[NSArray arrayWithObject:@"properties"]]];
        NSString *tempUserID = [[tempDict objectForKey:@"properties"] objectForKey:@"user_id"];
        NSLog(@"temp=%@",tempUserID);






        if (!IsEmpty(tempUserID))
        {
            [appDelegate.arr replaceObjectAtIndex:indexPath.row withObject:@"Twitter Logout"];
            cell.textLabel.text=@"Twitter Logout";
        }
        else
        {
             cell.textLabel.text=[appDelegate.arr objectAtIndex:indexPath.row];
        }



    }

    else if([[appDelegate.arr objectAtIndex:indexPath.row] isEqualToString:@"Facebook Login"])
    {
        if (appDelegate.session.isOpen) {
            [appDelegate.arr replaceObjectAtIndex:indexPath.row withObject:@"Facebook Logout"];
            cell.textLabel.text=[appDelegate.arr objectAtIndex:indexPath.row];
        }
        else
        {
           cell.textLabel.text=[appDelegate.arr objectAtIndex:indexPath.row]; 
        }


    }

    else
    {

         cell.textLabel.text=[appDelegate.arr objectAtIndex:indexPath.row];
    }




    return cell;


}

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{



    if([[appDelegate.arr objectAtIndex:indexPath.row]isEqualToString:@"Change Password"] && [chk isEqualToString:@"YES"])
    {   [UIView  beginAnimations:nil context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.75];



        ForgetPasswordViewController *forgetPassView=[[ ForgetPasswordViewController   alloc] initWithNibName:@"ForgetPasswordViewController" bundle:[NSBundle mainBundle]];
        NSLog(@"Working table");


        [self.navigationController pushViewController:forgetPassView animated:YES];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
        [UIView commitAnimations];



    }

    else if([[appDelegate.arr objectAtIndex:indexPath.row]isEqualToString:@"Facebook Login"])
    {
        if (appDelegate.session.state != FBSessionStateCreated) {
            // Create a new, logged out session.
            appDelegate.session = [[FBSession alloc] init];
        }
        [appDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                         FBSessionState status,
                                                         NSError *error) {
            // and here we make sure to update our UX according to the new session state
            if (appDelegate.session.isOpen) {

            [appDelegate.arr replaceObjectAtIndex:indexPath.row withObject:@"Facebook Logout"];
            [self.SettingsTable reloadData];
            }

        }];
1 голос
/ 10 сентября 2014

Я бы, вероятно, получил токен доступа в этом методе

func loginViewFetchedUserInfo(loginView: FBLoginView, user:FBGraphUser ) {
    println(FBSession.activeSession().accessTokenData.accessToken)
}

Этот код написан на языке Swift, но метод существует и для Obj C. Тогда вы будете использовать токен доступа в веб-представлении, как это предложили Сэнди и Стив

0 голосов
/ 15 ноября 2011

Получив токен FB access, вы сможете использовать API Faceboook JavaScript в своем веб-представлении. См. http://developers.facebook.com/docs/reference/javascript/ для официальной документации. Этот пост SO дает разумное объяснение: Получение токена доступа с использованием API Javascript . Как описано в этом посте, вы можете использовать токен доступа в вызове AJAX напрямую. Я не буду связываться с куки-файлами - просто передайте токен доступа.

Вы не объяснили, что именно вы хотите сделать с Facebook в веб-представлении, поэтому я не уверен, что это ответ на ваш вопрос на 100%. Я полагаю, вы знаете, как передать токен доступа в веб-представление (UIWebView's stringByEvaluatingJavaScriptFromString).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...