【问题标题】:How to load image to collectionview from url obtained from json如何从从json获得的url加载图像到collectionview
【发布时间】:2013-05-17 04:41:31
【问题描述】:

我有一个 IOS 应用程序,它使用 RestKit 将 json 格式的数据从服务器拉入 CoreData 实体。数据中的属性之一是与特定文章关联的图像的 URL。我正在尝试将该图像加载到我的 collectionViewController 中。这是我一直在尝试但没有成功的方法。

从内部

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 

我正在尝试这个

    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSURL *photoURL = [object valueForKey:@"imageUrl"];
    NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
    cell.cellimg = [[UIImage alloc] initWithData:photoData];
    [cell.title setText:[object valueForKey:@"title"]];

如果我注释掉抓取和加载图像的尝试,则视图会使用默认图像和从 json 数据接收到的文章标题很好地加载。基于此,我知道一切正常。

我还确定*photoData 被分配了正确的URL。但是每次我遇到NSData 行时,控制台都会打印出“-[__NSCFString isFileURL]: unrecognized selector sent to instance....”

老实说,我不知道这是否是正确的方法,或者它是否会起作用。我对此很陌生,所以任何帮助都会很棒。鉴于我是新手,一些小代码示例确实会有所帮助,并解释解决此问题的正确方法。

以防万一这是我定义*cellimg和*title的头文件

#import <UIKit/UIKit.h>

@interface GlobismNewsCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImage *cellimg;
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) NSURL *imageUrl;

@end

【问题讨论】:

  • 达姆比尔你成功了!谢谢!

标签: iphone ios json core-data restkit-0.20


【解决方案1】:

我认为您将NSString 用作NSURL。所以尝试使用这个...

NSURL *photoURL = [NSURL URLWithString:(NSString *) [object valueForKey:@"imageUrl"]];

【讨论】:

    【解决方案2】:

    感谢 Dharmbir,我在提出问题后的 25 分钟内解决了这个问题!

    为了澄清像我这样的新人,我更改了 Dharmbir 建议的行,所以块现在看起来像这样

    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSURL *photoURL = [NSURL URLWithString:(NSString *) [object valueForKey:@"imageUrl"]];
    NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
    [cell.cellimg setImage:[[UIImage alloc] initWithData:photoData]];        
    [cell.title setText:[object valueForKey:@"title"]];
    

    注意块中的第 4 行也从这里改变了

    cell.cellimg = [[UIImage alloc] initWithData:photoData];
    

    到这里

    [cell.cellimg setImage:[[UIImage alloc] initWithData:photoData]];
    

    我还必须将我的 *cellimg 属性更改为此

    @property (strong, nonatomic) IBOutlet UIImageView *cellimg;
    

    从这里

    @property (strong, nonatomic) IBOutlet UIImage *cellimg;
    

    我不得不更改为 UIImageView 类,因为我的故事板中的单元格基于 UIImageView 类。希望这对有需要的人有所帮助,再次感谢 Dharmbir!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 2016-07-18
      • 2016-10-31
      • 2016-04-05
      • 2019-02-03
      • 1970-01-01
      • 2020-01-29
      相关资源
      最近更新 更多