【问题标题】:How to post without post data using RestKit如何使用 RestKit 在没有发布数据的情况下发布
【发布时间】:2017-10-03 04:34:36
【问题描述】:
我正在寻找一种方法来映射要发布到端点的空对象。调用必须是POST,但不应该有任何数据发布到端点(空体),它只是直接调用端点没有数据。
我尝试使用与RestKit: How to handle empty response.body? 相同的技巧,但改用RKRequestDescriptor。
这样做会导致在RKObjectMapping 的postObject 方法中使用postData:nil 时出现以下错误:
未捕获的异常:RKRequestDescriptor 对象必须使用目标类为 NSMutableDictionary 的映射进行初始化,得到“NSNull”(参见 [RKObjectMapping requestMapping]);
使用NSNull 进行RKRequestDescriptor 的映射似乎可以工作,但nil 似乎无法进行映射操作。
【问题讨论】:
标签:
objective-c
post
null
restkit
nsmutabledictionary
【解决方案1】:
正如错误所述,它正在为映射操作寻找NSMutableDictionary。所以使用一个空的NSMutableDictionary 像@{} 而不是nil 的postObject 就可以了。
AFRKHTTPClient *client = [self getClient];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
RKObjectMapping *requestMapping = [RKObjectMapping mappingForClass:[NSNull class]];
[objectManager addRequestDescriptor:
[RKRequestDescriptor requestDescriptorWithMapping:requestMapping
objectClass:[NSNull class]
rootKeyPath:nil
method:RKRequestMethodAny]];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[NSNull class]];
[objectManager addResponseDescriptor:
[RKResponseDescriptor responseDescriptorWithMapping:responseMapping
method:RKRequestMethodPOST
pathPattern:nil
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];
[objectManager postObject:@{} // <-- this works, but nil doesn't
path:@"/api/some/endpoint"
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// succes code here
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// failure code here
}];