Facebook API - How to cancel Graph Request

后端 未结 9 1037
既然无缘
既然无缘 2020-12-16 04:06

I occasionally need to cancel a FaceBook graph request, but there seems to be no cancel or similar method in their API to do so. At the moment, crashes sometimes occur as th

相关标签:
9条回答
  • 2020-12-16 04:52

    Since SDK 3.1, it's very easy, as startWithCompletionHandler: returns a FBRequestConnection object, which has a -(void)cancel; method.

    For example:

    // In interface or .h definitions:
    @property (strong, nonatomic) FBRequest             *fBRequest;
    @property (strong, nonatomic) FBRequestConnection   *fbConnection;
    
    // when needed in class (params should be set elsewhere, this is just an example):
    self.fBRequest = [[FBRequest alloc] initWithSession:[FBSession activeSession] graphPath:@"me/photos" parameters:params HTTPMethod:@"POST"];
    self.fbConnection = [self.fBRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error){
        NSLog(@"Publish complete, error: %d", error.code);
    }];
    
    // now, to cancel anywhere in the class, just call:
    [self.fbConnection cancel];
    
    0 讨论(0)
  • 2020-12-16 04:59

    I've followed Matt Wilding's approach listed here, which was very useful, thanks Matt. Unfortunately it didnt quite work for me, so I made some tweaks and now it works... also this revised approach keeps out of the core facebook classes...

    //in .h define an FBRequest property
    @property (nonatomic, retain) FBRequest * pendingFBRequest;
    
    //in .m when making your request, store it in your FBRequest property
    pendingFBRequest = [facebook requestWithGraphPath:@"me/feed"
                                            andParams:params
                                        andHttpMethod:@"POST"
                                          andDelegate:self];
    
    //create a timer for your timeout
    pendingFacebookActionTimer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(onPendingFacebookActionTimeout) userInfo:nil repeats:NO];
    
    //cancel the action on the timeout's selector method
    -(void)onPendingFacebookActionTimeout {
    
        [pendingFBRequest.connection cancel];
    
    }
    
    0 讨论(0)
  • 2020-12-16 05:01

    Try this instead of using NSTimer:

    FBRequest *fbRequest = [facebook requestWithGraphPath:@"me" andDelegate:self];
    [self performSelector:@selector(fbRequestTimeout:) withObject:fbRequest afterDelay:30];
    
    - (void)fbRequestTimeout:(FBRequest *)fbRequest
    {
        [fbRequest.connection cancel];
        [fbRequest setDelegate:nil];
    }
    
    0 讨论(0)
提交回复
热议问题