Как программно добавить тестовых друзей в Facebook тестовых пользователей с помощью Facebook iOS SDK 3.14.1
Нам нужно, чтобы все наши тестовые пользователи были друзьями друг другу. Выполнение этого через панель инструментов приложения вручную - это огромный объем работы, в зависимости от количества нужных вам тестовых пользователей (в нашем случае более 50 тестовых пользователей).
Поэтому мы ищем способ сделать так, чтобы наши пользователи Facebook тестировали пользователей программно. Мы попробовали этот подход, следуя их веб-сайту здесь: https://developers.facebook.com/docs/graph-api/reference/v2.0/test-user/friends
Проблема заключается в том, что для того, чтобы отправить запрос на добавление в друзья от тестового пользователя 1, чтобы протестировать пользователя 2, необходимо войти в систему с помощью тестового пользователя 1, а для того, чтобы принять запрос на добавление в друзья, необходимо войти в систему с тестовым пользователем 2, в результате чего процесс еще хуже, чем добавление вручную с помощью панели инструментов приложения -> роли
Как мы можем сделать всех наших тестовых пользователей друзьями друг другу программно с помощью iOS SDK 3.14.1?
2 ответа
Было бы проще сделать это с веб-сервером.
Например, используя facebook-node-sdk:
Создать пользователя
FB.api('/v2.6/{app-id}/accounts/test-users', 'post', { fields: [{ installed: "true", permissions: "user_birthday user_friends email"}] }, function (res) { ... });
Сохранить вновь созданный идентификатор пользователя и access_token
Повторите шаги 1-2 по желанию
Отправить запрос на дружбу от пользователя A к пользователю B
FB.api('/v2.6/' + userA.fb_id + '/friends/' + userB.fb_id, { access_token: userA.access_token }, 'post', function (res) { ... });
Отправить запрос на добавление в друзья от пользователя B к пользователю A, чтобы принять
FB.api('/v2.6/' + userB.fb_id + '/friends/' + userA.fb_id, { access_token: userB.access_token }, 'post', function (res) { ... });
Если вы создаете своих пользователей программно, вы можете легко подружить их друг с другом.
https://developers.facebook.com/docs/graph-api/reference/v2.1/test-user/friends
#import "FBGraphObject.h"
@protocol FBTestGraphUser <FBGraphObject>
@property (nonatomic, readonly) NSString *id;
@property (nonatomic, readonly) NSString *access_token;
@property (nonatomic, readonly) NSString *login_url;
@property (nonatomic, readonly) NSString *email;
@property (nonatomic, readonly) NSString *password;
@property (nonatomic, retain) NSArray *friends;
@end
-(id<FBTestGraphUser>)createTestFacebook
{
NSString *appName = "";
NSString *userPrefix = [NSString stringWithFormat:@"%@User", appName];
NSString *facebookApplicationId = "";
NSString *facebookApplicationAccessToken = "";
NSString *url = [NSString stringWithFormat:@"https://graph.facebook.com/%@/accounts/test-users?installed=true&name=%@&locale=en_US&permissions=email,user_birthday,publish_actions&access_token=%@", facebookApplicationId, userPrefix, facebookApplicationAccessToken];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
return (id<FBTestGraphUser>)[FBGraphObject graphObjectWrappingDictionary:[data objectFromJSONData]];
}
-(void)deleteTestFacebookUser:(id<FBTestGraphUser>)testFacebookUser
{
NSLog(@"Deleting Facebook users...");
NSMutableArray* existingUsers = [NSMutableArray arrayWithArray:testFacebookUser.friends];
[existingUsers addObject:testFacebookUser];
NSOperationQueue* wipeUsers = [NSOperationQueue new];
[existingUsers enumerateObjectsUsingBlock:^(id<FBTestGraphUser> user, NSUInteger idx, BOOL *stop) {
[wipeUsers addOperationWithBlock:^{
[self deleteTestFacebookUser:user];
}];
}];
[wipeUsers waitUntilAllOperationsAreFinished];
NSLog(@"Done deleting Facebook users");
}
-(void)makeUser:(id<FBTestGraphUser>)userA friendsWithUser:(id<FBTestGraphUser>)userB {
// Don't try to parallelize this; you'll get unknown OAuth exceptions. -CS 2013-11-18
[self sendFriendRequestFrom:userA toUser:userB];
[self sendFriendRequestFrom:userB toUser:userA];
}
-(void)sendFriendRequestFrom:(id<FBTestGraphUser>)sender toUser:(id<FBTestGraphUser>)receiver {
NSString *url = [NSString stringWithFormat:@"https://graph.facebook.com/%@/friends/%@?access_token=%@", sender.id, receiver.id, sender.access_token];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)deleteTestFacebookUser:(id<FBTestGraphUser>)testFacebookUser
{
NSString *url = [NSString stringWithFormat:@"https://graph.facebook.com/%@?access_token=%@", testFacebookUser.id, WBTestCaseFacebookAppID];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"DELETE"];
NSError *error = nil;
NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}