2014-12-23 5 views
0

저는 iOS 프로그래밍에서 새로운입니다. 그래서 나는 초보자 용 질문을했습니다. AFNetworking 2를 시작했습니다. 그게 바로 작업입니다.AFNetworking을 통해 UICollectionView로 이미지를 다운로드하십시오.

요청했습니다. 응답은 두 번째 요청의 일부입니다. 첫 번째 요청이 끝날 때까지 기다려야한다는 의미입니다. 그들은 단계별로 따라합니다. 두 번째 응답을 받으면 구문 분석하여 20 개의 URL을 http://lalala-xx.jpg 형식으로 저장합니다. 그 후 이미지를로드하여 UICollectionView에 넣고 싶습니다. 범위에서 모든 것이 아니라 "다운로드 -> 셀에 똑바로"있는 방식으로하고 싶습니다. 나는 싱글 톤 클래스의 URL과 이미지를 저장하고 단지

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; 
    cell.imageView.image = [[UserData sharedUser].images objectAtIndex:indexPath.row]; 
    return cell; 
} 

처럼 그들에게 접근 할 수있는 Methos의 체인은 보이는

- (void)method1 
{ 
    NSString  *string = [NSString stringWithFormat:firstRequestString]; 
    NSURL  *url  = [NSURL URLWithString:string]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    operation.responseSerializer = [AFJSONResponseSerializer serializer]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     // getting needed part for second request 
     [self method2:(NSString *)part1]; 
    } 
    failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    { 
     // show error 
    }]; 

    [operation start]; 
} 

두 번째 방법은 같은 : 마지막

- (void)method2:(NSString *)part1 
{ 
    // lalala making secondRequestString 
    NSString  *string = [NSString stringWithFormat:secondRequestString]; 
    NSURL  *url  = [NSURL URLWithString:string]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    operation.responseSerializer = [AFJSONResponseSerializer serializer]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     NSMutableArray *imageURLs = [[NSMutableArray alloc] init]; 
     // getting needed URLs 
     [self loadAllImages:(NSMutableArray *)imageURLs]; 
    } 
    failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    { 
     // show error 
    }]; 

    [operation start]; 
} 

:

- (void)loadAllImages:(NSMutableArray *)imageURLs 
{ 
    // ??? 
} 

저는 stuc입니다. 케이. 다음에 무엇을해야합니까? 20 개의 URL이 있지만 이미지를 다운로드하여 ViewController로 보내서 셀의 이미지를 업데이트해야합니까? AFNetworkig에서 나에게 일부 작업 대기열을 제공 할 수 있습니다.
그리고 지금 내 코드가 마음에 들지 않습니다. 이 체인을 사용하지만 imgURL을 반환하는 독립적 인 메서드 2가 필요합니다. 그래서 그것은 보일 것입니다 : 사용자 버튼을 누르십시오 -> method1 -> method2 -> 그만. 사용자가 버튼을 누를 때까지 기다리십시오 -> download image1 -> show image1 -> download image2 -> show image2 -> 기타 등등 -> download imageN -> show imageN -> 중지하십시오. 반복하겠습니다. Array에 이미지를 저장해야합니다. 그 후에 사용하겠습니다. Thx u가 그것을 읽었습니다.

///////////////////////////////////////////////////////////////// /////////////////////

해결책을 찾았습니다. 그러나 그것은 나를 완전히 만족시키지 못합니다. 이미지는 무작위로옵니다. 순서대로로드하는 방법?

- (void)loadAllImages:(NSMutableArray *)imageURLs 
{   
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 

    for (NSURL *url in imageURLs) 
    { 
     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
     operation.responseSerializer = [AFImageResponseSerializer serializer]; 

     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
     { 
      [[UserData sharedUser].images addObject:responseObject]; 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectionViewRealoadData" object:nil]; 
     } 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     { 
      // show error 
     }]; 

     [manager.operationQueue addOperation:operation]; 
    } 
} 

답변

0

URL에서 데이터를 가져 와서 해당 데이터에서 UIImage 개체를 만들어야합니다. 당신이 당신의 이미지 객체 당신이 당신의 콜렉션 뷰의 데이터 소스로 사용 된 이미지의 배열에 추가 할 수 있습니다이 있으면

당신은 NSURL 방법

for(NSString *imgString in imageURLs){ 
    NSURL *url = [NSURL URLWithString:imgString]; 
    NSData *imgData = [NSData dataWithContentsOfURL:url]; 
    UIImage *img = [UIImage imageWithData:imgData ]; 

    [imageUrls addObject:img];//this mutable array should be initialized early in view controller life cycle (like ViewDidLoad). 
    } 

를 사용하여 URL에서 데이터를 얻을 수 있습니다. 당신이 새로운 데이터

내가 suppesed
+0

를 추가하면

[_collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:[imageUrls count] - 1 inSection:0]]]; 

//이 컬렉션 뷰를 다시로드'[_collectionView insertItemsAtIndexPaths : arrayWithIndexPaths]''[_collectionView reloadData] 더 나은 다음,' –

+0

예 그게 더 효율적으로 될 것입니다, 특히 이미지 세트가 커지면 내 대답을 편집했습니다. – JoshR604

관련 문제