gpt4 book ai didi

ios - 如何使用 AFIncrementalStore 在每个请求中添加身份验证 token ?

转载 作者:行者123 更新时间:2023-11-29 03:50:08 24 4
gpt4 key购买 nike

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

我已经根据本教程在我的 Rails 服务器上实现了 token 身份验证:http://matteomelani.wordpress.com/2011/10/17/authentication-for-mobile-devices/

我现在想要在从客户端到服务器的每个请求(包括 POST 请求)中包含 &auth_token=XXXXXXXX。我该怎么做?我还没有在这个相关帖子中找到解决方案:Using AFIncrementalStore with an Auth token

更新:这是我的第一次代码尝试,但似乎没有发送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。不过,相同的基本方法也可以使用,并且有 sample code at this answer这应该会为您指明正确的方向。


在所有情况下,您不能只将 &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 对象,而不是使用便捷方法(您可能没有),只需确保在 parameters 中包含 token 即可 创建 NSURLRequest 之前,如下所示:

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

关于ios - 如何使用 AFIncrementalStore 在每个请求中添加身份验证 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17154605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com