我正在使用 Restkit 的 RKObjectManager 和 RKObjectMapping 使用 GET 从 Web 服务中成功检索 JSON 数据。这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
RKURL *baseURL = [RKURL URLWithBaseURLString:@"http://192.168.1.12"];
RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:baseURL];
objectManager.client.baseURL = baseURL;
RKObjectMapping *markerMapping = [RKObjectMapping mappingForClass:[Marker class]];
[markerMapping mapKeyPath:@"la" toAttribute:@"lat"];
[markerMapping mapKeyPath:@"lo" toAttribute:@"lon"];
[markerMapping mapKeyPath:@"des" toAttribute:@"description"];
[objectManager.mappingProvider setMapping:markerMapping forKeyPath:@"markers"];
}
- (void)sendGet
{
NSString *lat = @"53.334932";
NSString *lon = @"-0.543749";
NSString *dist = @"1000";
NSDictionary *queryParams;
queryParams = [NSDictionary dictionaryWithObjectsAndKeys:lat, @"la", lon, @"lo", dist, @"d", nil];
RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKURL *URL = [RKURL URLWithBaseURL:[objectManager baseURL] resourcePath:@"/get_markers.php" queryParameters:queryParams];
[objectManager loadObjectsAtResourcePath:[NSString stringWithFormat:@"%@?%@", [URL resourcePath], [URL query]] delegate:self];
}
上面的代码正在运行,我很高兴使用返回的数据。但是,我无法发布要插入数据库的记录。我想我可以重用 sharedManager 甚至可能是映射。我不需要处理任何退货。
我尝试了以下片段的多种变体。无济于事。
第一个片段是尝试重用管理器和映射。忽略此伪代码中的映射范围,明显的缺陷是我无法弄清楚如何发布到正确的 URL 资源(baseURL & '/insert_marker.php')。所以我实际上没有尝试过这个:
- (void)postInsert
{
Marker *mkr = [Marker alloc];
mkr.lat = @"53.334933";
mkr.lon = @"-0.543750";
mkr.description = @"some words";
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager.mappingProvider setSerializationMapping:[markerMapping inverseMapping] forClass:[Marker class]];
[[RKObjectManager objectManager] postObject:mkr delegate:nil];
}
第二个片段运行但应用程序崩溃。显然,这在字符串和 url 类型之间存在混淆,但对象管理器帖子不会使用 url 进行编译。我很迷茫!
- (void)postInsert
{
RKParams* params = [RKParams params];
[params setValue:@"53.334933" forParam:@"la"];
[params setValue:@"-0.543750" forParam:@"l0"];
[params setValue:@"some words" forParam:@"des"];
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSString *URL = [RKURL URLWithBaseURL:[objectManager baseURL] resourcePath:@"/add_marker.php"];
[objectManager.client post:URL params:params delegate:nil];
}
那么,我如何使用参数发布(希望重用 sharedManager,也许是映射而不是处理返回)?