V
V
V2015-01-13 01:20:42
Objective-C
V, 2015-01-13 01:20:42

How to pull photos from Instagram and fill CollectionView cell with them?

Goodnight. I want to fill Collection View cells with photos from Instagram. I use SimpleAuth/Instagram to login and get an access token. I don't really understand how exactly to implement cell filling. Namudril of course already with the configuration of the cell. I will make a reservation that in the storyboard I have created a cell prototype, in which I placed a UIImage with tag 100, in fact, using this key, I refer to the image in the cell configuration.

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

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
Stanislav H, 2015-01-13
@ermolushka

in self.photos you store a json array of data objects, but not filenames on your device.

{
    "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
    },
    ...]
}

Do you need a link to the file, or the file itself
"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
            }
        },

you need to upload an image in each cell
- (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;
}

In general, it's better to load asynchronously =)
And even better, you can look towards InstagramKit

V
V, 2015-01-15
@ermolushka

In general, the problem is solved. I created a CollectionViewCell class and wrote something like this:

@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;
    
    
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question