Войдите в систему и добавьте друзей в Facebook с помощью Social Framework

Может ли кто-нибудь дать мне несколько советов о том, как интегрировать это? моя цель - получить список друзей, которые установили мое приложение (приложение fb). изначально мне нужно сначала войти в мое приложение и перечислить друзей, которые установили/не установили приложение.

PS: я не хочу использовать Facebook SDK. В прошлом мне снились кошмары из-за того, что facebook бесчисленное количество раз менял SDK.

=========== ОБНОВЛЕНИЕ

Я успешно вошел в систему и перечислил своих друзей на Facebook. Но теперь проблема с перечислением моего друга, у которого есть приложение и изображение списка. Я пробовал это:

URL: https://graph.facebook.com/me/friends?friends?fields=id,name,installed,picture

которые вызывают у меня OAuthException : An active access token must be used to query information about the current user. проблему.

Я пробовал также в API Graph работает без указанной ошибки.

если я попробую, только me/friends работает отлично, он выведет список всех моих друзей.


person HelmiB    schedule 31.01.2014    source источник
comment
Как это возможно? Я получаю только общее количество друзей.   -  person Teddy    schedule 08.02.2015


Ответы (2)


Сначала импортируйте структуру Social, Account, SystemConfiguration в свой проект. Затем используйте этот код в вашем файле .m

-(void)facebook
{
    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *key = @"XXXXXXXXXXXXX";//get your key form creating new app in facebook app section
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"email"],ACFacebookPermissionsKey, nil];

    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {
         if (granted)
         {
             NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
             //it will always be the last object with single sign on
             self.facebookAccount = [accounts lastObject];


             ACAccountCredential *facebookCredential = [self.facebookAccount credential];
             NSString *accessToken = [facebookCredential oauthToken];
             NSLog(@"Facebook Access Token: %@", accessToken);


             NSLog(@"facebook account =%@",self.facebookAccount);

             [self get];

             [self getFBFriends];

             isFacebookAvailable = 1;
         } else
         {
             //Fail gracefully...
             NSLog(@"error getting permission yupeeeeeee %@",e);
             sleep(10);
             NSLog(@"awake from sleep");
             isFacebookAvailable = 0;

         }
     }];
   }

-(void)get
{

    NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me"];

    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
    request.account = self.facebookAccount;

    [request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {

        if(!error)
        {

            NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            NSLog(@"Dictionary contains: %@", list );

            fbID = [NSString stringWithFormat:@"%@", [list objectForKey:@"id"]];
            globalFBID = fbID;

            gender = [NSString stringWithFormat:@"%@", [list objectForKey:@"gender"]];
            playerGender = [NSString stringWithFormat:@"%@", gender];
            NSLog(@"Gender : %@", playerGender);


            self.globalmailID   = [NSString stringWithFormat:@"%@",[list objectForKey:@"email"]];
            NSLog(@"global mail ID : %@",globalmailID);

              fbname = [NSString stringWithFormat:@"%@",[list objectForKey:@"name"]];
            NSLog(@"faceboooookkkk name %@",fbname);

            if([list objectForKey:@"error"]!=nil)
            {
                [self attemptRenewCredentials];
            }
            dispatch_async(dispatch_get_main_queue(),^{

            });
        }
        else
        {
            //handle error gracefully
            NSLog(@"error from get%@",error);
            //attempt to revalidate credentials
        }

    }];

    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *key = @"451805654875339";
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"friends_videos"],ACFacebookPermissionsKey, nil];


    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {}];

}



-(void)getFBFriends
{

    NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me/friends"];

    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
    request.account = self.facebookAccount;

    [request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {

        if(!error)
        {

            NSDictionary *friendslist =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            for (id facebookFriendList in [friendslist objectForKey:@"data"])
            {
                NSDictionary *friendList = (NSDictionary *)facebookFriendList;
                [facebookFriendIDArray addObject:[friendList objectForKey:@"id"]];
            }


            if([friendslist objectForKey:@"error"]!=nil)
            {
                [self attemptRenewCredentials];
            }
            dispatch_async(dispatch_get_main_queue(),^{

            });
        }
        else
        {
            //handle error gracefully
            NSLog(@"error from get%@",error);
            //attempt to revalidate credentials
        }

    }];

    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *key = @"451805654875339";
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"friends_videos"],ACFacebookPermissionsKey, nil];


    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {}];

}


-(void)accountChanged:(NSNotification *)notification
{
    [self attemptRenewCredentials];
}

-(void)attemptRenewCredentials
{
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error)
        {
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");
                    [self get];
                    break;
                case ACAccountCredentialRenewResultRejected:
                    NSLog(@"User declined permission");
                    break;
                case ACAccountCredentialRenewResultFailed:
                    NSLog(@"non-user-initiated cancel, you may attempt to retry");
                    break;
                default:
                    break;
            }

        }
        else{
            //handle error gracefully
            NSLog(@"error from renew credentials%@",error);
        }
    }];
}
person Gajendra Rawat    schedule 31.01.2014
comment
благодаря. но получение друзей на Facebook работает, но моя проблема заключается в том, чтобы найти друзей, которые установили мое приложение на Facebook. - person HelmiB; 31.01.2014
comment
graph.facebook.com/user_id/friends?fields=id,name, установлено Вы пробовали это в URL - person Gajendra Rawat; 31.01.2014
comment
OAuthException : для запроса информации о текущем пользователе необходимо использовать активный токен доступа. проблема. Эта ошибка возникает из-за токена доступа. Для ее устранения вам необходимо получить токен доступа. - person Gajendra Rawat; 31.01.2014
comment
Проверьте мой собственный ответ. нельзя добавлять поля внутри URL-адреса графика. надеюсь, что кто-то найдет это полезным. - person HelmiB; 31.01.2014

Наконец-то я понял, видимо, вы не можете добавить URL-адрес. вам нужно передать поля в параметре внутри SLRequest

NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me/friends"];

NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:@"picture,id,name,installed",@"fields", nil];

SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                        requestMethod:SLRequestMethodGET
                                                  URL:requestURL
                                           parameters:param];
person HelmiB    schedule 31.01.2014