iOS Facebook Graph API使用“下一页”或“上一页”Url进行分页使用SDK

时间:2014-07-01 15:37:30

标签: ios facebook-graph-api facebook-ios-sdk

当我想要使用" next"时,我不太确定最好的方法或适当的SDK调用。或"之前"分页结果分页时由图表api返回的URL。我已经查看了FBRequest和FBRequestConnection的文档,但是没有任何方法或调用可以作为我问题的明显解决方案。任何人都有一个或可以提出一个能指出正确方向的建议吗?

3 个答案:

答案 0 :(得分:8)

要获得下一个链接,您必须这样做:

我用这种方式解决了这个问题:

添加标题

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

和代码

//use this general method with any parameters you want. All requests will be handled correctly

- (void)makeFBRequestToPath:(NSString *)aPath withParameters:(NSDictionary *)parameters success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure
{
    //create array to store results of multiple requests
    NSMutableArray *recievedDataStorage = [NSMutableArray new];

    //run requests with array to store results in
    [self p_requestFriendsFromPath:aPath
                        parameters:parameters
                           storage:recievedDataStorage
                            succes:success
                           failure:failure];
}




 - (void)p_requestFromPath:(NSString *)path parameters:(NSDictionary *)params storage:(NSMutableArray *)friends succes:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure
{
    //create requests with needed parameters
        FBSDKGraphRequest *fbRequest = [[FBSDKGraphRequest alloc]initWithGraphPath:path
                                                                         parameters:params
                                                                         HTTPMethod:nil];

    //then make a Facebook connection
    FBSDKGraphRequestConnection *connection = [FBSDKGraphRequestConnection new];
    [connection addRequest:fbRequest
         completionHandler:^(FBSDKGraphRequestConnection *connection, NSDictionary*result, NSError *error) {

             //if error pass it in a failure block and exit out of method
             if (error){
                 if(failure){
                    failure(error);
                 }
                 return ;
             }
             //add recieved data to array
             [friends addObjectsFromArray:result[@"data"];
             //then get parameters of link for the next page of data
             NSDictionary *paramsOfNextPage = [FBSDKUtility dictionaryWithQueryString:result[@"paging"][@"next"]];
             if (paramsOfNextPage.allKeys.count > 0){
                 [self p_requestFromPath:path
                              parameters:paramsOfNextPage
                                 storage:friends
                                  succes:success
                                 failure:failure];
                 //just exit out of the method body if next link was found
                 return;
             }
             if (success){
                success([friends copy]);
             }
         }];
     //do not forget to run connection
    [connection start];
}

使用方法:

获取好友列表使用技巧如下:

//For example retrieve friends list with limit of retrieving data items per request equal to 5

NSDictionary *anyParametersYouWant = @{@"limit":@5};
[self makeFBRequestToPath:@"me/taggable_friends/"
           withParameters:anyParametersYouWant
                  success:^(NSArray *results) {
                      NSLog(@"Found friends are:\n%@",results);    
                  }
                  failure:^[(NSError *) {
                      NSLog(@"Oops! Something went wrong(\n%@",error);
                  }];
];

答案 1 :(得分:8)

尼古拉的解决方案非常完美。这是它的Swift版本

func makeFBRequestToPath(aPath:String, withParameters:Dictionary<String, AnyObject>, success successBlock: (Array<AnyObject>?) -> (), failure failureBlock: (NSError?) -> ())
{
    //create array to store results of multiple requests
    let recievedDataStorage:Array<AnyObject> = Array<AnyObject>()

    //run requests with array to store results in
    p_requestFromPath(aPath, parameters: withParameters, storage: recievedDataStorage, success: successBlock, failure: failureBlock)
}


func p_requestFromPath(path:String, parameters params:Dictionary<String, AnyObject>, var storage friends:Array<AnyObject>, success successBlock: (Array<AnyObject>?) -> (), failure failureBlock: (NSError?) -> ())
{
    //create requests with needed parameters


    let req = FBSDKGraphRequest(graphPath: path, parameters: params, tokenString: FBSDKAccessToken.currentAccessToken().tokenString, version: nil, HTTPMethod: "GET")
    req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
        if(error == nil)
        {
            print("result \(result)")

            let result:Dictionary<String, AnyObject> = result as! Dictionary<String, AnyObject>


            //add recieved data to array
            friends.append(result["data"]!)
            //then get parameters of link for the next page of data

            let nextCursor:String? = result["paging"]!["next"]! as? String

            if let _ = nextCursor
            {
                let paramsOfNextPage:Dictionary = FBSDKUtility.dictionaryWithQueryString(nextCursor!)

                if paramsOfNextPage.keys.count > 0
                {
                    self.p_requestFromPath(path, parameters: paramsOfNextPage as! Dictionary<String, AnyObject>, storage: friends, success:successBlock, failure: failureBlock)
                    //just exit out of the method body if next link was found
                    return
                }
            }

            successBlock(friends)
        }
        else
        {
            //if error pass it in a failure block and exit out of method
            print("error \(error)")
            failureBlock(error)
        }
    })
}


func getFBFriendsList()
{
    //For example retrieve friends list with limit of retrieving data items per request equal to 5
    let anyParametersYouWant:Dictionary = ["limit":2]
    makeFBRequestToPath("/me/friends/", withParameters: anyParametersYouWant, success: { (results:Array<AnyObject>?) -> () in
        print("Found friends are: \(results)")
        }) { (error:NSError?) -> () in
            print("Oops! Something went wrong \(error)")
    }
}

答案 2 :(得分:3)

所以在我寻找一个明显的答案时,我偶然发现了github.com上的Facebook iOS SDK源代码,发现了这个类:https://github.com/facebook/facebook-ios-sdk/blob/master/src/Network/FBGraphObjectPagingLoader.m

在&#34; - (void)followNextLink&#34;方法我找到了我的解决方案:

 FBRequest *request = [[FBRequest alloc] initWithSession:self.session
                                                  graphPath:nil];

    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    [connection addRequest:request completionHandler:
     ^(FBRequestConnection *innerConnection, id result, NSError *error) {
         _isResultFromCache = _isResultFromCache || innerConnection.isResultFromCache;
         [innerConnection retain];
         self.connection = nil;
         [self requestCompleted:innerConnection result:result error:error];
         [innerConnection release];
     }];

    // Override the URL using the one passed back in 'next'.
    NSURL *url = [NSURL URLWithString:self.nextLink];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    connection.urlRequest = urlRequest;

    self.nextLink = nil;

    self.connection = connection;
    [self.connection startWithCacheIdentity:self.cacheIdentity
                      skipRoundtripIfCached:self.skipRoundtripIfCached];

上面有很多我不需要的代码,所以我能够(在SO OP的帮助下)将其浓缩为:

/* make the API call */
FBRequest *request = [[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:nil];
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithDictionary:@{@"friends": [result objectForKey:@"data"], @"paging": [result objectForKey:@"paging"]}];
    NSLog(@"%@", dictionary);
    block(dictionary, error);
}];

// Override the URL using the one passed back in 'next|previous'.
NSURL *url = [NSURL URLWithString:paginationUrl];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];
connection.urlRequest = urlRequest;

[connection start];

为了帮助可能需要更通用方法的其他人,我已将我的大部分Facebook API图表调用编入@ https://gist.github.com/tamitutor/c65c262d8343d433cf7f找到的要点。