如何使用AFIncrementalStore在每个请求中添加一个Auth令牌?

我有一个iOS + Rails 3.1应用程序,我正在使用AFIncrementalStore进行客户端 – 服务器通信。

我已经根据这个教程在我的Rails服务器上实现了令牌authentication: http : //matteomelani.wordpress.com/2011/10/17/authentication-for-mobile-devices/

我现在要在客户端到服务器的每个请求中包含&auth_token=XXXXXXXX ,包括POST请求。 我该怎么做? 我还没有find在这个相关的职位的解决scheme: 使用AFIncrementalStore与身份validation令牌

更新:这是我的第一次代码尝试,但似乎并没有发送auth_token

(在我的AFIncrementalStoreHTTPClient子类中)

 - (NSMutableURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest withContext:(NSManagedObjectContext *)context { NSMutableURLRequest *request = [[super requestForFetchRequest:fetchRequest withContext:context] mutableCopy]; NSMutableString *requestBody = [[NSMutableString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; [requestBody appendFormat:@"&%@=%@", @"auth_token", @"xkT2eqqdoNp5y4vQy7xA"]; [request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]]; return request; } 

更新 :我撇去你的问题(对不起!),我下面的示例代码适用于常规的AFHTTPClient,而不是AFIncrementalStore。 尽pipe如此,相同的基本方法仍然有效,并且在这个答案中有示例代码应该指向正确的方向。


在任何情况下,您都不能只将&auth_token=whatever附加到HTTP正文的末尾。

你可能想重写你的getPath...postPath...方法,如:

 - (void)getPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { if (parameters) { // Make a mutable copy and add the "token" parameter to the dictionary NSMutableDictionary *mutableParams = [parameters mutableCopy]; [mutableParams setObject:@"whatever" forKey:@"token"]; parameters = [NSDictionary dictionaryWithDictionary:mutableParams]; } else { parameters = @{@"token" : @"whatever"}; } [super getPath:path parameters:parameters success:success failure:failure]; } 

这种方法将允许AFNetworking根据您的特定请求和编码设置对您的参数进行适当的编码。

如果你正在使用自己的AFHTTPRequestOperation对象,而不是使用便捷方法(你可能不需要),那么只要确保在创buildNSURLRequest 之前parameters包含在parameters 如下所示:

 NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters]; 
Interesting Posts