1

我可以使用 Instagram API 检索我需要的内容,但是(我的理解)是因为 AFNetworking 异步运行,代码直接跳转到我的 CollectionView 方法中,但我的 AFNetworking 调用仍在工作,CollectionView 单元格永远不会加载。没有准备好阵列。使用[操作waitUntilFinished];但似乎什么也没做。

代码在这里,谢谢!

-(void)viewDidLoad {

    [super viewDidLoad];

    NSString *path = @"https://api.instagram.com/v1/tags/snow/media/recent?access_token=836379.f59def8.fd07b9ba8ea440188dc56d2763bbf6c2";

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];

    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

                                                        imageArray = [[[[JSON valueForKey:@"data"]valueForKey:@"images"]valueForKey:@"low_resolution"]valueForKey:@"url"];




                                                        for (id item in imageArray) {


                                                            [images addObject:item];

                                                        }



                                                    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
                                                        // NSLog(@"There was a problem: %@", [error localizedDescription]);
                                                    }];

    [operation start];
    [operation waitUntilFinished];  // DOES NOT STOP AND WAIT

}


- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {

/* RETURNS ARRAY COUNT OF ZER0 HERE, BUT I AM EXPECTING A VALID ARRAY OF URLS!

   return  [imageArray count];
}

- (CollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"CellZero" forIndexPath:indexPath];

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}
4

3 回答 3

0

将所有图像添加到 imageArray 后,在网络请求的成功块中重新加载集合视图数据:UICollectionView reloadData

另请查看valueForKeypath,它可以帮助您摆脱那些嵌套的 valueForKey 调用。

于 2013-11-06T22:46:55.747 回答
0

答案很简单。在您的成功回调块中,只需调用

[self.collectionView reloadData];

这可确保在 AFNetworking 库成功从 Instagram API 获取数据后重新加载集合视图。实际上,我要做的是在另一个名为“reloadCollectionViewWithImages:(NSArray *)imageArray”的方法中重构回调函数:

- (void)reloadCollectionViewWithImages:(NSArray *)imageArray {
    for (id item in imageArray) {
        [images addObject:item];
    }
    [self.collectionView reloadData];
}

并在成功回调中调用此方法。

如果您有任何其他问题,请发表评论:)

于 2013-11-06T22:47:37.830 回答
0

添加 [self.collectionView reloadData]; 效果很好。谢谢 两个答案同时出现。但只能检查一个。感谢双方!

于 2013-11-07T18:03:23.630 回答