Using AFIncrementalStore with an Auth token

2020-06-24 06:01发布

问题:

I'm working on an iOS client for App.net, and I'd like to use AFIncrementalStore to sync the web service with my Core Data implementation in the app.

I've gotten the two to work for API requests that don't require an auth token, but I can't figure out how to use the auth token with AFIncrementalStore.

In other words, I'm able to pull down the global feed, since it doesn't require auth:

https://alpha-api.app.net/stream/0/posts/stream/global

...however, to get a user's stream, you need auth (you'll note this link gives an error):

https://alpha-api.app.net/stream/0/posts/stream

I understand that I need to append an auth_token to the end of the API call, but I'm not sure how to do that using AFIncrementalStore.

Update: Here's the chunk of code that currently gets the global stream:

This is a method pulled directly from the example App.net project included in AFIncrementalStore.

-(NSURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest withContext:(NSManagedObjectContext *)context {
    NSMutableURLRequest *mutableURLRequest = nil;
    if ([fetchRequest.entityName isEqualToString:@"Post"]) {
        mutableURLRequest = [self requestWithMethod:@"GET" path:@"stream/0/posts/stream/global" parameters:nil];
    }

    return mutableURLRequest;
}

回答1:

All you have to do with the case above to alter it to correctly use an access token is add parameters to the request instead of passing nil.

To build the parameters simply make an NSDictionary with the keys and values you need. For example in some of my App.net code I have this

NSDictionary *params = @{@"access_token": token};

Using the new compiler directives this builds an NSDictionary with a single key (in this case 'access_token') with the value in the NSString token.

After you have this just make your request something like:

[self requestWithMethod:@"GET" path:@"stream/0/posts/stream" parameters:params];

To pass the parameters in the request.

Let me know if this isn't clear enough!