ios - CollectionView 委托(delegate)在 URL 连接完成之前调用

标签 ios objective-c uicollectionview nsurl

我正在实现一个带有 URL 连接的 CollectionView。

我遇到的问题如下,在 URL 连接完成之前调用了 collectionView 委托(delegate)。因此,Collection View 不会获取任何要显示的数据,或者我如何重新加载 collection view。

这是我的实现。

-(id)init{
    self = [super init];
    if (self){
        [self loadFromURL];
    }
    return self;
}

-(void)loadFromURL{

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:
                                [NSURL URLWithString:@"http://www.appybyte.com/satgitsin/products.php?zip=77072"]];

    NSURLConnection *theConnection=[[NSURLConnection alloc]
                                    initWithRequest:theRequest delegate:self];
    if(theConnection){
        responseData = [[NSMutableData alloc] init];
    } else {
        NSLog(@"failed");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSString *msg = [NSString stringWithFormat:@"Failed: %@", [error description]];
    NSLog(@"%@",msg);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves  error:&myError];

    self.pElements = [[NSMutableArray alloc] init];
    for (NSDictionary *aModuleDict in res){
        PMosaicData *aMosaicModule = [[PMosaicData alloc] initWithDictionary:aModuleDict];
        [self.pElements addObject:aMosaicModule];
    }

}

#pragma mark - UICollectionViewDataSource

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

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.pElements count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    PMosaicCell *pCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    PMosaicData *pData=[self.pElements objectAtIndex:indexPath.row];
    pCell.pMosaicData = pData;
    return pCell;
}

顺便说一句,我的 collectionView 在另一个名为 CustomViewController.h 的类中定义为 __weak IBOutlet UICollectionView *_collectionView; 我怎么能让它工作?

最佳答案

在 connectionDidFinishLoading 结束时:调用 [self.collectionView reloadData]。

我建议使用 NSURLConnection 的类方法 sendAsynchronousRequest:queue:options:error: 而不是委托(delegate)模式,因为您没有执行任何自定义缓冲逻辑。

最终代码应该是这样的:

-(void)loadFromURL {
    NSURL *url = [NSURL URLWithString:@"http://www.appybyte.com/satgitsin/products.php?zip=77072"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    __weak typeof(self) weakSelf = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSError *myError = nil;
        NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

        // probably should handle the error here
        if (myError) {

        }

        weakSelf.pElements = [[NSMutableArray alloc] init];
        for (NSDictionary *aModuleDict in res){
            PMosaicData *aMosaicModule = [[PMosaicData alloc] initWithDictionary:aModuleDict];
            [weakSelf.pElements addObject:aMosaicModule];
        }

        [weakSelf.collectionView reloadData];
    }];
}

关于ios - CollectionView 委托(delegate)在 URL 连接完成之前调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661989/

相关文章:

ios - 点击 UITableViewCell 时如何正确显示 UINavigationController?

ios - 原型(prototype)单元的自定义 UI 元素无法访问 xcode 6 beta

ios - 在 UITextView 中定位 UILabel

ios - 在PreparetoSegue期间检索所选UICollectionViewCell的索引路径?

ios - NSKeyedUnarchiver 无法理解的存档

ios - numberformatter(样式货币)删除不起作用

ios - 选择器 rac 发送异步请求没有已知的类方法

ios - 单击一个 View Controller 中的按钮将在另一个 View Controller 中推进进度条

ios - Collection View 拖放延迟

ios - 单击tableview Cell中的Collectionview时如何找到tableview的索引路径