使用 RKParams 向 API 发布帖子并使用 RestKit 使用 RKObjectMapping 映射响应
Posted
技术标签:
【中文标题】使用 RKParams 向 API 发布帖子并使用 RestKit 使用 RKObjectMapping 映射响应【英文标题】:Making a post to API with RKParams and mapping the response with RKObjectMapping using RestKit 【发布时间】:2012-05-25 19:30:51 【问题描述】:现在我正在对我的代码进行大规模重构,并且我想统一我使用 Restkit 的方式。我对我的 API 服务器和 REST 调用进行 RPC 调用的方法是分开的。
使用 objectMapping 进行的 REST 调用和使用 RKClient 进行的 RPC 调用。除此之外,我使用块而不是委托,这很好,但我对它的工作原理有些怀疑。
这是我之前的代码,它可以很好地发布对象并使用委托手动进行映射,之后是使用不发送参数的块的新代码。
//This was the old way...
- (void) upload: (KFMedia *) pic
RKParams* imageParams = [RKParams params];
NSData* imageData = UIImageJPEGRepresentation(pic.image, 0.7f);
[imageParams setData:imageData MIMEType:@"image/jpg" forParam:@"FileUpload"];
[[RKClient sharedClient] post:@"/api/upload/" params:imageParams delegate:self];
//This is the new way I'm trying...
- (void) upload: (KFMedia *) pic onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock
RKParams* imageParams = [RKParams params];
NSData* imageData = UIImageJPEGRepresentation(pic.image, 0.7f);
[imageParams setData:imageData MIMEType:@"image/jpg" forParam:@"FileUpload"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/api/upload/" usingBlock:^(RKObjectLoader *loader)
//Trying to set params here, but it seems that I'm not sending anything :(
loader.params = imageParams;
loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[KFMedia class]];
loader.delegate = self;
loader.onDidLoadObject = loadBlock;
loader.onDidFailWithError = failBlock;
loader.onDidFailLoadWithError = failBlock;
loader.onDidLoadResponse = ^(RKResponse *response)
[self fireErrorBlock:failBlock onErrorInResponse:response];
;
];
我发送的请求的正文为空,这意味着参数未正确发送或设置。关于如何让它发挥作用的任何想法?
【问题讨论】:
【参考方案1】:我刚刚解决了这个问题。要使用 loadObjectsAtResourcePath 发送额外的参数,您必须强制使用
loader.method = RKRequestMethodPOST;
代码如下:
- (void) upload: (KFMedia *) pic onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock
RKParams* imageParams = [RKParams params];
NSData* imageData = UIImageJPEGRepresentation(pic.image, 0.7f);
[imageParams setData:imageData MIMEType:@"image/jpg" forParam:@"FileUpload"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/api/upload/" usingBlock:^(RKObjectLoader *loader)
loader.method = RKRequestMethodPOST; //This line solved the problem
loader.params = imageParams;
loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[KFMedia class]];
loader.delegate = self;
loader.onDidLoadObject = loadBlock;
loader.onDidFailWithError = failBlock;
loader.onDidFailLoadWithError = failBlock;
loader.onDidLoadResponse = ^(RKResponse *response)
[self fireErrorBlock:failBlock onErrorInResponse:response];
;
];
【讨论】:
以上是关于使用 RKParams 向 API 发布帖子并使用 RestKit 使用 RKObjectMapping 映射响应的主要内容,如果未能解决你的问题,请参考以下文章