初学者使用RestKit,我的第一个例子是foursquare API,我使用了RestKit和Blocks而不是代表。
我想要检索场地名称,这是JSON响应
这是我的代码:
// App Delegate.m
RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURLString:@"https://api.Foursquare.com/v2"];
RKManagedObjectStore *objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"Venue.sqlite"];
objectManager.objectStore = objectStore;
objectManager.serializationMIMEType = RKMIMETypeJSON;
RKManagedObjectMapping *venueMapping = [RKManagedObjectMapping mappingForClass:[Venue class] inManagedObjectStore:objectStore];
[venueMapping mapKeyPath:@"id" toAttribute:@"id"];
[venueMapping mapKeyPath:@"name" toAttribute:@"name"];
venueMapping.primaryKeyAttribute = @"id";
[objectManager.mappingProvider setMapping:venueMapping forKeyPath:@"response.venue"];
然后在myViewController.m
-(void)loadVenues{
// When caling loadObjectsAtResourcePath method it specify RKObjectLoader which is the actual request.
// within these block you can take more options to controll the request.
[[RKObjectManager sharedManager]loadObjectsAtResourcePath:@"/venues/40a55d80f964a52020f31ee3?oauth_token=FNQPN5P5EKLJ5IQ44TMWO00I3W033M0Y1TKINW2OTF2VIOTP&v=20130512" usingBlock:^(RKObjectLoader* loader)
{
loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Venue class]];
loader.onDidLoadObject = ^(NSArray *objects)
{
NSLog(@"onDidLoadObject Blocks");
self.data = objects;
[self.tableView reloadData];
};
}
];
}
并且应用程序正在进入onDidLoadObject块,但每次数组都是空的!! 即使我在浏览器上测试链接,它也会附带数据。
当我调试loader.URL时,它总是带有这些
https://api.Foursquare.com/v2/venues/40a55d80f964a52020f31ee3?v=20130512&oauth_token=FNQPN5P5EKLJ5IQ44TMWO00I3W033M0Y1TKINW2OTF2VIOTP - https://api.Foursquare.com/v2 - https://api.Foursquare.com/v2
我不知道为什么load.URL错了?!
我认为你用错误的方式调用4square API,任何人都可以提供帮助吗? :)
答案 0 :(得分:0)
我对上述代码有两个疑虑:
1-显然上面的JSON响应,只列出一个Venue ..所以KeyPath应该是“response.venue”而不是“response.venues”
2- ID的映射在哪里? ..哪个是RestKit用于插入数据库的主键?您需要设置主键映射。
答案 1 :(得分:0)
- 将您的映射作为要从所有应用程序类访问的类方法,并且只执行一次。
- 更改属性“id”,因为它在Objective-C中保留。
- 将此添加到块
[loader setObjectMapping:[RestKitMapping yourMapping]];
- 然后将其与您的映射代码
一起添加[objectManager.mappingProvider setMapping:venueMapping forKeyPath:@"response.venue"];
- 并使用代表而不是块