现在我正在学习如何使用 JSON 从网络获取数据。我想为我的每篇文章获取一张图片(来自 Rails 应用程序)。按照树屋图书馆教程,我将不得不做这样的事情:
表视图控制器.m
self.upcomingReleases = [NSMutableArray array];
NSArray *upcomingReleasesArray = [dataDictionary objectForKey:@"upcoming_releases"];
for (NSDictionary *upcomingReleaseDictionary in upcomingReleasesArray) {
UpcomingRelease *upcomingRelease = [UpcomingRelease upcomingReleaseWithReleaseName:[upcomingReleaseDictionary objectForKey:@"release_name"]];
upcomingRelease.thumbnail = [upcomingReleaseDictionary objectForKey:@"thumbnail"];
upcomingRelease.url = [NSURL URLWithString:[upcomingReleaseDictionary objectForKey:@"url"]];
[self.upcomingReleases addObject:upcomingRelease];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UpcomingRelease *upcomingRelease = [self.upcomingReleases objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:upcomingRelease.thumbnailURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
cell.textLabel.text = upcomingRelease.release_name;
return cell;
}
即将发布.h
@property (nonatomic, strong) NSString *release_name;
@property (nonatomic, strong) NSString *thumbnail;
@property (nonatomic, strong) NSURL *url;
//Designated Initializer
- (id) initWithReleaseName:(NSString *)release_name;
+ (id) upcomingReleaseWithReleaseName:(NSString *)release_name;
- (NSURL *) thumbnailURL;
- (NSString *) formattedDate;
@end
即将发布.m
- (NSURL *) thumbnailURL {
return [NSURL URLWithString:self.thumbnail];
}
我应该用我自己的字符串替换所有“缩略图”。问题是我的图像在一个嵌套对象内,并且不止 1 个。我想从我的每个帖子中的第一个 image_file 调用拇指的 URL。我怎样才能做到这一点?
谢谢。
我的 JSON API
upcoming_releases: [
{
id: 2,
release_name: "Nike Lebron X Low",
release_price: "165",
release_colorway: "Raspberry-Red/Blueprint-Court",
release_date: "2013-09-07T00:00:00.000Z",
url: "http://obscure-lake-7450.herokuapp.com/upcoming/2",
images: [
{
image_file: {
image_file: {
url: "https://s3.amazonaws.com/soleresource/uploads/releases/nike-lebron-x-low-raspberry.jpg",
thumb: {
url: "https://s3.amazonaws.com/soleresource/uploads/releases/thumb_nike-lebron-x-low-raspberry.jpg"
}
}
}
},
{
image_file: {
image_file: {
url: "https://s3.amazonaws.com/soleresource/uploads/releases/nike-lebron-x-low-raspberry-2.jpg",
thumb: {
url: "https://s3.amazonaws.com/soleresource/uploads/releases/thumb_nike-lebron-x-low-raspberry-2.jpg"
}
}
}
},
]
}