【发布时间】:2014-10-02 08:57:33
【问题描述】:
我在 UIView 旁边有一个 UIImageView,它在 JSON 数组中显示一个对象 @"photos",如下所示:http://topmobiletrends.com/wp-content/uploads/2013/10/screen568x568-14.jpeg
我的 NSLog 告诉我所有对象都已正确解析。但是UIViews里面的UIImageViews显示的是同一张图片,我相信它是第一个对象[0]。我需要让视图显示@“photos”键的所有对象的每个图像。
这是我的 ViewController.m 代码:
。 . .
@interface ViewController ()
{
NSInteger index;
}
//@property (nonatomic, weak)NSURL *imageURL;
@end
@implementation ViewController
@synthesize menuButton;
@synthesize myImage;
@synthesize priceLabel;
-(void)viewDidLoad{
[super viewDidLoad];
NSURL *bburl = [NSURL URLWithString:@"http://www.suchandsuch.com/api/sites"];
NSData *jsonData = [NSData dataWithContentsOfURL:bburl];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:bburl];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:bburl completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){
NSLog(@"%@", response);
NSData *data = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *imageURLString = [[[dataDictionary objectForKey:@"sites"] objectAtIndex:index] objectForKey:@"photo"];
NSURL *imageURL = [NSURL URLWithString:[imageURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"sites : %@", imageURLString);
NSArray *sitesArray = [dataDictionary objectForKey:@"sites"];
NSMutableArray *photos = [[NSMutableArray alloc]initWithArray:sitesArray];
for (NSDictionary *item in sitesArray) {
MyObject *current = [MyObject alloc];
current.name = [item objectForKey:@"name"];
current.url = [item objectForKey:@"url"];
current.price = [item objectForKey:@"price"];
current.photo = [item objectForKey:@"photo"];
[photos addObject:current];
NSLog(@"%@", current.photo);
}
for (MyObject *photo in photos)
{
dispatch_async(dispatch_get_main_queue(),^{
UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(30,30,258,229)];
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
imageView.frame = CGRectMake(30, 30, 258, 229);
//Get image from url
[self.imageView setImageWithURL:imageURL];
//[self.myImage addSubview:imageView];
[dView addSubview:imageView];
[self.view addSubview:dView];
// priceLabel.text = [[[dataDictionary objectForKey:@"sites"] objectAtIndex:index] objectForKey:@"price"];
});
}
}];
[task resume];
}
【问题讨论】:
-
也许 for 循环可以解决问题?...
标签: ios arrays json indexing uiimageview