几个月后更新
真正的答案是loader.params 创建了HTTP BODY,因此它适用于POST, PUT, DELETE 等,但不适用于GET,其中参数附加到URL。
因此,如果您遇到GET 的相同问题,以下答案仍然有效,但如果您发送GET 请求,则主要使用将参数附加到查询字符串的方法。
总结一下两者的区别。
在 HTTP 正文中发送参数(即POST, UPDATE, DELETE)
// Convert a NS Dictionary into Params
RKParams *params = [RKParams paramsWithDictionary:optionValues];
// I use sendObject to skip the router. Otherwise it's normally postObject
[[RKObjectManager sharedManager] sendObject:yourObject toResourcePath: yourResourcePath usingBlock:^(RKObjectLoader *loader) {
loader.method = RKRequestMethodPOST;
loader.delegate = delegate;
loader.params = params; // This sets params in the POST body and discards your yourObject mapping
} ];
注意事项(以上)
在块中设置参数会破坏您可能在yourObject 中设置的任何映射,这有点违背了使用对象映射的目的。 Sebastian loader.params - Extra params 在这里提供了一个修复,如果您真的想使用此方法将额外参数附加到您的 Post 而不是对象中。
以查询字符串的形式发送参数(即GET)
// Make a NS dictionary and use stringByAppendingQueryParameters
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
@"limit",@"20",
@"location",@"latitude,longitude",
nil];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/api/v1/shops.json" stringByAppendingQueryParameters:shopParams] delegate:objectDelegate];
其余答案仅供参考,我是囤积者。
旧答案
我在我的项目中使用 RestKit 并面临同样的问题。
我认为RKParams主要是用来做POST的请求。我无法完全破译您的代码,因为 1) 我不知道 loader 的声明? 2)RKParams不能和Object Manager一起使用?
我做到了。
App Delegate 中的加载器方法
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:@"limit",@"30", nil];
[[RKClient sharedClient] get:@"/api/v1/shops.json" queryParams:shopParams delegate:self];
委托
- (void)requestDidStartLoad:(RKRequest *)request {
NSLog(@"RK Request description: %@",[request description]);
}
输出:
RK Request description: <RKRequest: 0x7993db0> 和 rails 日志说 {"limit"=>"30"}。
从 Xcode 的自动完成功能中,您可以看到 get 请求甚至没有使用 RKParams。只是一个NSDict。 POST 请求使用它。
我的目标是将查询字符串(即?location=singapore&etcetc)附加到我在 Rails 中的 API 方法中。为此,RK 附带了一个名为 appendQueryParams RK docs link 的 NSString 插件,您可以使用它来附加查询参数。
如果你的目标是POST图片等,你可以按照上面的思路使用RKClient。
更新:
如果您只想将参数附加到对象管理器
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
@"limit",@"20",
@"location",@"latitude,longitude",
nil];
这已过时并标记为弃用。
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/api/v1/shops.json" appendQueryParams:shopParams] delegate:self];
改用这个:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[@"/api/v1/shops.json stringByAppendingQueryParameters:shopParams] delegate:yourLoaderDelegate];
Rails 日志:{"location"=>"latitude,longitude", "limit"=>"20"}
希望我的回答没有做出任何错误的陈述。
参考这个问题RestKit GET query parameters。