简体   繁体   English

JSON中的数据未在UICollectionView中更新

[英]Data from JSON not updating in UICollectionView

I'm creating an app with a Newsfeed as a UICollectionView however it doesn't seem to update when I change the JSON file. 我正在创建一个使用Newsfeed作为UICollectionView的应用程序,但是当我更改JSON文件时它似乎没有更新。 I am using a UIRefreshControl to refresh it but I can't tell if my issue is to do with this or to do with how the JSON is read (or something else entirely). 我正在使用UIRefreshControl刷新它,但是我无法确定我的问题是与此有关还是与JSON的读取方式有关(或与之完全无关)。

viewDidLoad 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 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];
}

refresh 刷新

- (void)refresh:(id)sender
{

    [self fetchFeed];

    [(UIRefreshControl *)sender endRefreshing];

    NSLog(@"Refreshed");
}

Any help will be really appreciated. 任何帮助将不胜感激。

Collection View Data Source 集合视图数据源

#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];
}

Try to this 试试这个

- (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]; 
}

If NSLog(@"%@", self.articles) works and shows data you have proven that you are getting network data back. 如果NSLog(@"%@", self.articles)可以正常工作并显示数据,则表明您已证明自己正在获取网络数据。 Did you set up your UIView as the delegate and the datasource properly? 您是否将UIView正确设置为代理和数据源? This is usually done at the top of the UIViewController class and looks like this: 通常在UIViewController类的顶部完成此操作,如下所示:

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

One way to check if the datasource is set up correctly is to set a breakpoint here 检查数据源是否正确设置的一种方法是在此处设置断点

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

When you call 你打电话时

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

this will in turn call cellForItemAtIndexPath to display data. 这将依次调用cellForItemAtIndexPath来显示数据。 If cellForItemAtIndexPath isn't called then you have not properly set your UICollectionViewDataSource 如果未调用cellForItemAtIndexPath,则您没有正确设置UICollectionViewDataSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM