来自JSON的数据没有在UICollectionView中更新

问题描述:

我创建了一个带有Newsfeed的应用程序作为UICollectionView,但是当我更改JSON文件时它似乎没有更新。我正在使用UIRefreshControl来刷新它,但我不知道我的问题是与此有关还是与如何阅读JSON(或其他完全)有关。来自JSON的数据没有在UICollectionView中更新

viewDidLoad中

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 


    self.navigationItem.title = @"News"; 

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn.frame = CGRectMake(0,0,23,16); 
    [btn setBackgroundImage:[UIImage imageNamed:@"menuImage.png"] forState:UIControlStateNormal]; 
    [btn addTarget:(NavigationViewController *)self.navigationController action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside]; 
    UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn]; 
    self.navigationItem.leftBarButtonItem = barBtn; 

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    _session = [NSURLSession sessionWithConfiguration:config 
              delegate:self 
             delegateQueue:nil]; 
    [self fetchFeed]; 



    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 

    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat frameWidth = screenRect.size.width - 20; 
    CGFloat frameHeight = screenRect.size.height - 20; 

    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(10, 10, frameWidth, frameHeight) collectionViewLayout:layout]; 
    [_collectionView setDataSource: self]; 
    [_collectionView setDelegate: self]; 

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [_collectionView setBackgroundColor:[UIColor clearColor]]; 


    [self.view addSubview:_collectionView]; 



    UIRefreshControl * refreshControl = [[UIRefreshControl alloc] init]; 
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refresh Images"]; 
    [_collectionView addSubview:refreshControl]; 
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged]; 

    [self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]]; 
    [self.collectionView reloadData]; 

} 

fetchFeed

- (void)fetchFeed 
{ 
    NSString *requestString = @"http://www.jameslester.xyz/example.json"; 
    NSURL *url = [NSURL URLWithString:requestString]; 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 

    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req 
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
             NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data 
                            options:0 
                            error:nil]; 
             self.articles = jsonObject[@"articles"]; 

             NSLog(@"%@", self.articles); 
             NSLog(@"Feed Fetched!!!"); 

             dispatch_async(dispatch_get_main_queue(), ^{[self.collectionView reloadData]; 
            }); 
            }]; 


    [dataTask resume]; 
} 

刷新

- (void)refresh:(id)sender 
{ 

    [self fetchFeed]; 

    [(UIRefreshControl *)sender endRefreshing]; 

    NSLog(@"Refreshed"); 
} 

任何帮助将非常感激。

集合视图数据源

#define LABEL_TAG 100001 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    UILabel *articleTitle = [cell.contentView viewWithTag:LABEL_TAG]; 
    NSDictionary *article = self.articles[indexPath.row]; 

    if (!articleTitle) { 
     articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(5, cell.bounds.size.height - cell.bounds.size.height/2.2, cell.bounds.size.width - 10, cell.bounds.size.height/2)]; 
     articleTitle.textColor = [UIColor whiteColor]; 
     articleTitle.numberOfLines = 3; 
     articleTitle.adjustsFontSizeToFitWidth = YES; 
     articleTitle.tag = LABEL_TAG; 
     [cell.contentView addSubview:articleTitle]; 
    } 

    articleTitle.text = article[@"title"]; 

    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[@"image"]]]; 

    UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]]; 

    [bgImageView setContentMode:UIViewContentModeScaleAspectFill]; 
    [bgImageView setClipsToBounds:YES]; 

    CAGradientLayer *gradient = [CAGradientLayer layer]; 
    gradient.frame = CGRectMake(0, cell.bounds.size.height - cell.bounds.size.height/2, cell.bounds.size.width, cell.bounds.size.height/2); 
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil]; 
    //gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:0.5], nil]; 
    [bgImageView.layer insertSublayer:gradient atIndex:0]; 

    cell.backgroundView = bgImageView; 

    return cell; 
} 


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section 
{ 
    return 10; // This is the minimum inter item spacing, can be more 
} 


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section 
{ 
    return 10; 
} 


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 

    int x = screenWidth/2 - 15; 
    int y = x; 

    return CGSizeMake(x, y); 
} 


- (void)collectionView:(UICollectionView *)colView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath 
{ 
    NSDictionary *article = self.articles[indexPath.row]; 
    NSURL *URL = [NSURL URLWithString:article[@"url"]]; 

    self.webViewController.title = article[@"title"]; 
    self.webViewController.URL = URL; 
    [self.navigationController pushViewController:self.webViewController 
             animated:YES]; 
} 
+0

分享你的收藏查看数据源的方法实现 –

+0

尝试将此[_collectionView reloadData]下dispatch_get_main_queue() –

+0

嗨m.davlet,我很新的这(这只是我的第一个应用程序)当你说收集视图数据源方法时,你要求什么。你在谈论cellForItemAtIndexPath方法吗? – ghertyish

尝试这个

- (void)fetchFeed { 
    NSString *requestString = @"http://www.jameslester.xyz/example.json"; 
    NSURL *url = [NSURL URLWithString:requestString]; 
    NSURLRequest*req = [NSURLRequest requestWithURL:url]; 

    NSURLSessionDataTask*dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    self.articles = jsonObject[@"articles"]; 
    NSLog(@"%@", self.articles); 
    NSLog(@"Feed Fetched!!!"); 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      [_collectionView reloadData]; 
     }); 
    }]; 
    [dataTask resume]; 
} 
+0

嗨Ravi,我只是试过这个,但它似乎仍然不会更新 – ghertyish

如果NSLog(@"%@", self.articles)作品,并显示数据,你已经证明了你所得到的网络数据备份。你是否将UIView设置为代理和数据源?这通常是在UIViewController类的顶部做,看起来是这样的:检查

class MyClassName: UICollectionViewDataSource { 
    // Your code here. 
} 

的一种方式,如果数据源设置正确的在这里设置一个断点

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    print(“This shows that I’m getting called”) 
    // Your custom code 
} 

当您打电话

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self.collectionView reloadData]; 
}) 

这将依次调用cellForItemAtIndexPath来显示数据。如果cellForItemAtIndexPath不那么叫你没有正确设置你的UICollectionViewDataSource

+0

嗨,我有信息显示在CollectionViewCells中,当我把一个消息放在cellForItemAtIndexPath它被调用。我的问题是当我更新JSON并尝试刷新它不会,它保持与相同的单元格。如果我重置模拟器,那么它似乎读取更新的JSON,但我希望它更新,只要我拉刷新。 – ghertyish