Facebook API - How to cancel Graph Request

后端 未结 9 1038
既然无缘
既然无缘 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:45

    For those of us who build the static library and are unable to access the implementation files, a category would be the best way to go.

    For those of us who did not build the static library, using a category would be optimal as well because you don't need to modify the existing files.

    Here is said category.

    // Facebook+Cancel.h
    #import "Facebook.h"
    
    @interface Facebook (Facebook_cancel)
    
    - (void)cancelPendingRequest:(FBRequest *)releasingRequest;
    
    - (void)cancelAllRequests;
    
    @end
    

    And then the .m file

    // Facebook+Cancel.m
    #import "Facebook+Facebook_cancel.h"
    
    @implementation Facebook (Facebook_cancel)
    
    - (void)cancelPendingRequest:(FBRequest *)releasingRequest{
        [releasingRequest.connection cancel];
        if ([_requests containsObject:releasingRequest]) {
            [_requests removeObject:releasingRequest];
            [releasingRequest removeObserver:self forKeyPath:@"state"];
    
        }
    }
    
    - (void)cancelAllRequests {
        for (FBRequest *req in [_requests mutableCopy]) {
            [_requests removeObject:req];
            [req.connection cancel];
            [req removeObserver:self forKeyPath:@"state"];
        }
    }
    
    @end
    

    For those using any other answer, you are causing a memory leak. The Facebook SDK will warn you through NSLog that you have not removed an observer. The fourth line in the cancelAllRequests method fixes this problem.

提交回复
热议问题