嗨我试图将图像从json显示到CollectionView。
我的代码是......
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://zoo.com/jh/image.php"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *headlines=[jsonArray1 objectForKey:@"image_gallery"];
for (int i=0;i<[headlines count]; i++)
{
NSString *moblinks=[[headlines objectAtIndex:i]objectForKey:@"image_url"];
[self.itemshowdetailsAr objectAtIndex:moblinks];
NSLog(@"%@",moblinks);
}
和我在控制台中的结果
2014-06-20 15:05:27.005 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_1.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_2.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_3.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_4.jpg
2014-06-20 15:05:27.008 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_5.jpg
2014-06-20 15:05:27.008 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_6.jpg
我的collectionview代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
NSString *ImageURL =[self.itemshowdetailsAr objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
cell.imageView.image = [UIImage imageWithData:imageData];
cell.imageView.userInteractionEnabled=YES;
cell.imageView.contentMode = UIViewContentModeScaleToFill;
// cell.imageView.tag=i-1;
return cell;
}
但我只收到了空的Collection View。我犯了错误?我在控制台中获得了一些url但是cell没有显示图像。
答案 0 :(得分:0)
从它的外观来看,你试图在主线程上下载图像,我猜测在处理网络请求时UI可能会冻结。而是通过执行类似
的操作异步加载图像并远离主线程- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self.itemshowdetailsAr objectAtIndex:indexPath.row]]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.imageView.image = [UIImage imageWithData:data];
cell.imageView.userInteractionEnabled=YES;
cell.imageView.contentMode = UIViewContentModeScaleToFill;
}];
}] resume];
return cell;
}
NSURLSession任务将远离主线程。下载imageData时将调用完成处理程序。此时,操作将添加到主线程以更新collectionViewCell中的imageView。