@ermolushka

Как вытащить фотки из Instagram и заполнить ими CollectionView cell?

Доброй ночи. Хочу заполнить ячейки Collection View фотками из Instagram. Использую SimpleAuth/Instagram для входа и получения access token. Не очень понимаю, как именно реализовать заполнение ячейки. Намудрил конечно уже с конфигурацией ячейки. Оговорюсь, что в сториборде у меня создан прототип ячейки, в которую я поместил UIImage с тэгом 100, собственно по этому ключу и обращаюсь к изображению в конфигурации ячейки.

#import "PhotosCollectionViewController.h"
#import <SimpleAuth/SimpleAuth.h>
#import "AFNetworking.h"

@interface PhotosCollectionViewController ()

@property (nonatomic) NSString *accessToken;
@property (nonatomic) NSArray *photos;

@end

@implementation PhotosCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.accessToken = [userDefaults objectForKey:@"accessToken"];
    
    if (self.accessToken == nil) {
        
        SimpleAuth.configuration[@"instagram"] = @{
                                                   @"client_id" : @"ХХХ",
                                                   SimpleAuthRedirectURIKey : @"ХХХ"
                                                   };
        
        
        [SimpleAuth authorize:@"instagram" completion:^(NSDictionary *responseObject, NSError *error) {
            
            NSString *accessToken = responseObject[@"credentials"][@"token"];
            [userDefaults setObject:accessToken forKey:@"accessToken"];
            [userDefaults synchronize];
        }];
    } else{
        
        NSString *string = [[NSString alloc] initWithFormat:@"https://api.instagram.com/v1/tags/snow/media/recent?access_token=%@",self.accessToken];
        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) {
            
          self.photos = [responseObject objectForKey:@"data"];
           
            
          //  self.photos = [[[[responseObject valueForKey:@"data"]valueForKey:@"images"]valueForKey:@"low_resolution"]valueForKey:@"url"];
            [self.collectionView reloadData];
            
            NSLog(@"%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Request Failed: %@, %@", error, error.userInfo);    }
         ];
        
        [operation start];
    }
}

#pragma mark <UICollectionViewDataSource>

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


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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
    NSDictionary *img = [self.photos objectAtIndex:indexPath.row];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    recipeImageView.image = [UIImage imageNamed:[img objectForKey:@"images"]];    
    return cell;
}
  • Вопрос задан
  • 2976 просмотров
Решения вопроса 1
@shomishinec
Software Developer
в self.photos вы храните массив json объектов data, но никак не имена файлов на вашем устройстве.

{
    "data": [{
        "type": "image",
        "users_in_photo": [],
        "filter": "Earlybird",
        "tags": ["snow"],
        "comments": {
            "data": [{
                "created_time": "1296703540",
                "text": "Snow",
                "from": {
                    "username": "emohatch",
                    "username": "Dave",
                    "id": "1242695"
                },
                "id": "26589964"
            },
            {
                "created_time": "1296707889",
                "text": "#snow",
                "from": {
                    "username": "emohatch",
                    "username": "Emo Hatch",
                    "id": "1242695"
                },
                "id": "26609649"
            }],
            "count": 3
        }
        "caption": {
            "created_time": "1296703540",
            "text": "#Snow",
            "from": {
                "username": "emohatch",
                "id": "1242695"
            },
            "id": "26589964"
        },
        "likes": {
            "count": 1,
            "data": [{
                "username": "mikeyk",
                "full_name": "Mike Krieger",
                "id": "4",
                "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1242695_75sq_1293915800.jpg"
            }]
        },        
        "link": "http://instagr.am/p/BWl6P/",
        "user": {
            "username": "emohatch",
            "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1242695_75sq_1293915800.jpg",
            "id": "1242695",
            "full_name": "Dave"
        },
        "created_time": "1296703536",
        "images": {
            "low_resolution": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
                "width": 306,
                "height": 306
            },
            "thumbnail": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
                "width": 150,
                "height": 150
            },
            "standard_resolution": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
                "width": 612,
                "height": 612
            }
        },
        "id": "22699663",
        "location": null
    },
    ...]
}


А вам нужна ссылка на файл, либо сам файл
"images": {
            "low_resolution": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
                "width": 306,
                "height": 306
            },
            "thumbnail": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
                "width": 150,
                "height": 150
            },
            "standard_resolution": {
                "url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
                "width": 612,
                "height": 612
            }
        },


надо загрузить картинку в каждую ячейку
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
   NSString *url = [self.photos objectAtIndex:indexPath.row][@"images"][@"thumbnail"][@"url"];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
 recipeImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
    return cell;
}


А вообще лучше загружать асинхронно =)
А еще лучше можно глянуть в сторону InstagramKit
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@ermolushka Автор вопроса
В общем проблема решена. Я создал класс CollectionViewCell и прописал примерно следующее:

@implementation PhotosCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.accessToken = [userDefaults objectForKey:@"accessToken"];
    
    if (self.accessToken == nil) {
        
        SimpleAuth.configuration[@"instagram"] = @{
                                                   @"client_id" : @"XXX",
                                                   SimpleAuthRedirectURIKey : @"XXX"
                                                   };
        
        
        [SimpleAuth authorize:@"instagram" completion:^(NSDictionary *responseObject, NSError *error) {
            
            NSString *accessToken = responseObject[@"credentials"][@"token"];
            [userDefaults setObject:accessToken forKey:@"accessToken"];
            [userDefaults synchronize];
        }];
    } else{
        
        NSString *string = [[NSString alloc] initWithFormat:@"https://api.instagram.com/v1/users/{user-id}/media/recent?access_token=%@",self.accessToken];
        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) {
            
            //self.photos = [responseObject objectForKey:@"data"];
            
            self.photos = [[[[responseObject valueForKey:@"data"]valueForKey:@"images"]valueForKey:@"low_resolution"]valueForKey:@"url"];
            
            
            [self.collectionView reloadData];
            //NSLog(@"%@",responseObject);
            NSLog(@"%@", self.photos);
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Request Failed: %@, %@", error, error.userInfo);    }
         ];
        
        [operation start];
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark <UICollectionViewDataSource>

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


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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
   

    NSString *url = [self.photos objectAtIndex:indexPath.row];
    cell.image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
    return cell;
    
    
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы