我正在尝试显示来自网络服务的解析图像,但我的图像没有显示。我意识到在视图加载后图像被添加到数组中。那么,我如何让图像显示在集合视图上?更好的是,应该在主线程之外执行哪一行代码以便加载图像?谢谢您的帮助。
#import "ShowImagesCollectionViewController.h"
#import "ImageCell.h"
@interface ShowImagesCollectionViewController (){
NSMutableArray *array;
}
@property(nonatomic, strong)NSURLConnection *connection;
@property(nonatomic, strong)NSMutableData *webdata;
@end
@implementation ShowImagesCollectionViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self getData];
array = [[NSMutableArray alloc]initWith];
[_collectionView reloadData];
}
-(void)getData
{
[_activyIndicator startAnimating];
NSURL *url = [NSURL URLWithString:@"WEBSITE"];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
_connection = [NSURLConnection connectionWithRequest:requestURL delegate:self];
if (_connection) {
_webdata = [[NSMutableData alloc]init];
}
}
联系
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_webdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Fail With error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[_activyIndicator startAnimating];
NSDictionary *allDataDictionary =[NSJSONSerialization JSONObjectWithData:_webdata options:kNilOptions error:nil];
NSDictionary *currentShowDictionary = [allDataDictionary objectForKey:@"Current_Show"];
NSArray *photoArray =[currentShowDictionary objectForKey:@"Photos"];
for (NSDictionary *diction in photoArray) {
NSDictionary *photo_urlDictionary = [diction objectForKey:@"photo_url"];
// NSLog(@"%@",photo_urlDictionary);
NSURL *collectionURL = [NSURL URLWithString:[photo_urlDictionary objectForKey:@"url"]];
NSData *colectionImageData = [NSData dataWithContentsOfURL:collectionURL];
UIImage *collectionImage = [UIImage imageWithData:colectionImageData];
[array addObject:collectionImage];
NSLog(@"%@",array);
}
[_activyIndicator stopAnimating];
}
集合视图
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [array count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pictureCell" forIndexPath:indexPath];
NSString *myImageString = [array objectAtIndex:indexPath.row];
cell.pictureImageView.image = [UIImage imageNamed:myImageString];
return cell;
}