I'm calling this API and it's jsonobject in a segue, and trying to push it into a view controller, but it's not carrying the data. In my Below code it prints just fine in the call, but the other two prints come up with null.
Is there something I'm missing to make the data persistent?
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showChangeDetail"]) {
NSIndexPath *indexPath = nil;
BNRItem *item = nil;
//BDItemChangeDetailAPI *itemAPI = nil;
NSArray *items = [[BNRItemStore sharedStore] allItems];
if (self.searchDisplayController.active) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
item = [searchResults objectAtIndex:indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
//item = items[indexPath.row];
item = [items objectAtIndex:indexPath.row];
}
NSLog(#"111111%#", self.APIItem);
[self fetchFeedAPIChangeDetail];
NSLog(#"222222%#", self.APIItem);
BDChangeApproveController *destViewController = segue.destinationViewController;
destViewController.itemAPI = self.APIItem;
}
}
- (void)fetchFeedAPIChangeDetail
{
//NSString *changeorder = changeOrder;
// NSString *requestString = [#"http://URL.com];
NSString *requestString = #"http://URL.com";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error){
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
//NSLog(#"%#", jsonObject1);
self.APIItem = jsonObject1[#"CoDetail"];
NSLog(#"%#", self.APIItem);
}];
[dataTask resume];
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// show loading indicator
__weak typeof(self) weakSelf = self;
[[BNRItemStore sharedStore] fetchFeedAPIChangeDetail:^(NSArray *array, NSError *err)
{
[weakSelf performSegueWithIdentifier:#"showChangeDetail" sender:weakSelf];
// hide loading indicator
}];
}
Related
How to get value from json?
this is first api
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/countries/?format=json"];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedUrlAsString = [urlAsString stringByAddingPercentEncodingWithAllowedCharacters:set];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
arr = [jsonResponse valueForKey:#"countries"];
NSLog(#"%#",arr);
[self.tableView reloadData];
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(#"error : %#", error.description);
}
}] resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
cell.textLabel.text = [arr objectAtIndex:indexPath.row ];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *str = [arr objectAtIndex:indexPath.row] ;
ViewController1 *vc=[self.storyboard instantiateViewControllerWithIdentifier:#"ViewController1"];
vc.str1 = [arr objectAtIndex:indexPath.row];
[self.navigationController pushViewController:vc animated:YES];
}
this is second one
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/India/on/2001-05-11/?format=json"];
NSString *encodedString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
// _str2 = [jsonResponse valueForKey:#"dob"];
/// NSLog(#"%#",_str2);
NSLog(#"%#",jsonResponse);
}
}
}
}
when i click particular country i should get data from that country
you need to use that str1 property that you are setting in didSelect method to make your URL, so replace the India with str1's value.
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/%#/on/2001-05-11/?format=json", self.str1];
Note: You need to give proper name to your property, so better if you changed str1 to selectedCountry or something else.
I am calling the following method in didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath{
[self unreadMessageCounter];
}
In that method I am getting a value with parameter name "MsgCount". For that the written code is.
-(void) unreadMessageCounter{
NSUserDefaults *defaultUser=[NSUserDefaults standardUserDefaults];
NSString* username = [defaultUser objectForKey:KUserName];
NSString* password = [defaultUser objectForKey:KPassword];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
});
NSString *url3 ;
NSString *base_url=[[NSUserDefaults standardUserDefaults] objectForKey:#"BASE_URL"];
url3=[[NSString alloc]initWithFormat:#"%#%#? username=%#&password=%#&deviceUniqueId=%#",base_url,MESSAGE_COUNTER,username,password,[defaultUser objectForKey:KDeviceToken]];
[defaultUser synchronize];
NSURL *requestURL = [NSURL URLWithString:[url3 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:requestURL];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *urlResponse, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)urlResponse;
NSLog(#"Response Code For Message Counter:: %ld", (long)[response statusCode]);
if(response){
NSMutableDictionary *returneDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Return Dict For Message Counter:: %#", returneDict);
if (returneDict != nil) {
if ([returneDict valueForKey:#"valueSet"]){
for (NSDictionary *dict in [returneDict valueForKey:#"valueList"]) {
_counterNumber = dict[#"MsgCount"];
NSLog(#"counter number %#", _counterNumber);
}
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}
}
}];
[task resume];
}
After that I am passing that _counterNumber string to the next view controller with the help of prepareForSegue, for that the following code is.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if (![segue.identifier isEqualToString:#"Show Notification"]) {
UINavigationController *nav = [segue destinationViewController];
WelcomeScreenViewController *welcomeScreenViewController = (WelcomeScreenViewController *)nav.topViewController;
welcomeScreenViewController.counterString = _counterNumber;
}
}
It was going to the next view controller but on the first call, after didselectrowatindexpath instead of unreadMessageCounter method, prepareForSegue is getting call that's why the _counterNumber value I am getting nil, but on the second time when I am calling then It is working as usual. So plese help me in that case because I am not getting any clue.
First Disconnect your segue from cell to nextViewController. And make new segue from current ViewController to your nextViewController like below screenshot
And after processing you API that you are calling in didSelectRowAtIndexPath perform segue through code like below.
[self performSegueWithIdentifier: #"Show Notification" sender: self];
I making here simple application on XCODE 7.1. I just display 2 label and 1 image in tableview cell.I am parsing data from this URL. I am simply load data in TableviewHere i put the code of ViewController.m file
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.alpha = 1.0;
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
[activityIndicator startAnimating];//to start animating
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
}
}];
[dataTask resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *Identifier = #"mycell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier];
// Set and load the images
[cell.imageView sd_setImageWithURL:[_imageURL objectAtIndex:indexPath.row] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
// Get rid of the activity indicator when the image has been loaded
}];
cell.textLabel.text = [_country objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [_population objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//NSString *rowValue = self.friends[indexPath.row+1];
NSString *message = [[NSString alloc] initWithFormat:#"You selected %#",[_country objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"YOU SELECT"
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I am using AFNetworking 3.0 and SDWebImage for image loading.Data parse successfully and and displayed in tableview.I attached screenshot below
Problem is what the all data are not displayed in the tableview cell i also put the Alert dialog on each cell of tableview data successfully loaded but not displayed in cell. I search everywhere i can't find solution for this i am using 3G connection so net speed is not an issue Please someone help.
Try to reload table view with updated data in completion block.
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
//Added Code -> Reloading data on Main queue for update
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableview reloadData];
});
}
}];
[dataTask resume];
Hope, it'll help you.
Thanks.
1) Parse Data and after getting data relaod table
-(void)ParseData
{
NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: #"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
//Create URLReques
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Set Method POST/GET
[request setHTTPMethod:#"GET"];
// Asynchronously Api is hit here
NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) //If error nil
{
//Serialization data
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"json %#",json);
array=[json valueForKey:#"worldpopulation"];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if(array.count!=0)
{
//Reload table View
[_tblView reloadData];
}
});
}
else
{
//failure;
}
}];
[dataTask resume] ; // Executed task
}
2) Table View DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(array.count!=0)
{
return [array count];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
//= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.backgroundColor =[UIColor whiteColor];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *lblCountry=(UILabel*)[cell viewWithTag:2];
lblCountry.text= [[array objectAtIndex:indexPath.row]valueForKey:#"country"];
UILabel *lblPopulation=(UILabel*)[cell viewWithTag:3];
lblPopulation.text= [[array objectAtIndex:indexPath.row]valueForKey:#"population"];
UIImageView *img = (UIImageView *)[cell viewWithTag:1];
[img setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row]valueForKey:#"flag"]]];
return cell;
}
I'm trying to build an app that uses data from this url: http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss
So far, I'm downloading it with this:
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
self.issueData = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
// Log the data for debugging
NSLog(#"DownloadedData:%#",self.issueData);
// Use dispatch_async to update the table on the main thread
// Remember that NSURLSession is downloading in the background
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}] resume];
}
and trying to insert it into my table view cells with this:
- (CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row];
cell.title.text = [thread objectForKey:#"description"];
cell.date.text = [thread objectForKey:#"publishedDate"];
cell.content.text = [thread objectForKey:#"contentSnippet"];
return cell;
Anyone know what I'm doing wrong?
Your top level object for json is not array so
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row]; this will not work. You top level object is dictionary so parsing will be as
(CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectForKey:#"responseData"];
NSDictionary *feed = [thread objectForKey:#"feed"];
cell.title.text = [feed objectForKey:#"description"];
NSArray *entries = [feed objectForKey:#"entries"];
NSDictionary *posts = entries[indexPath.row];
cell.date.text = [posts objectForKey:#"publishedDate"];
cell.content.text = [posts objectForKey:#"contentSnippet"];
return cell;
}
I guess right way for parsing it as follow's
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
NSDictionary * dict;
dict= [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
dispatch_async(dispatch_get_main_queue(), ^{
if ([dict valueForKey:#"responseData"]) {
if([[dict valueForKey:#"responseData"] isKindOfClass:[NSDictionary class]]){
if ([(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]) {
if ([[(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]isKindOfClass:[NSDictionary class]]) {
NSDictionary * feedDict = [(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"];
if ([feedDict valueForKey:#"description"]){
NSLog(#"%#",[feedDict valueForKey:#"description"]);
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]]){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"published = %#",[dic valueForKey:#"publishedDate"]);
}
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]] ){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"contentSnippet = %#",[dic valueForKey:#"contentSnippet"]);
}
}
}
}
}
}
});
}] resume];}
I just logged the required keys to console you can add them to arrays and use them anywhere you want.
As you can see I have two methods tuula and wendyslookbook. Then I call them both in my mostPopular method. I have requested the photos from the Instagram API but now I want to put these two user photos together. How can I do that?
//
// PhotosViewController.m
// Photo Bombers
//
// Created by Alex Macleod on 20/8/14.
// Copyright (c) 2014 Alex Macleod. All rights reserved.
//
#import "PhotosViewController.h"
#import "PhotoCell.h"
#import "DetailViewController.h"
#import "PresentDetailTransition.h"
#import "DismissDetailTransition.h"
#import <SimpleAuth/SimpleAuth.h>
#interface PhotosViewController () <UIViewControllerTransitioningDelegate>
#property (nonatomic) NSString *accessToken;
#property (nonatomic) NSArray *photos;
#end
#implementation PhotosViewController
- (instancetype) init {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(106.0, 106.0);
layout.minimumInteritemSpacing = 1.0;
layout.minimumLineSpacing = 1.0;
return (self = [super initWithCollectionViewLayout:layout]);
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Fashun";
[self.collectionView registerClass:[PhotoCell class] forCellWithReuseIdentifier:#"photo"];
self.collectionView.backgroundColor = [UIColor whiteColor];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.accessToken = [userDefaults objectForKey:#"accessToken"];
if (self.accessToken == nil) {
[SimpleAuth authorize:#"instagram" options:#{#"scope": #[#"likes"]} completion:^(NSDictionary *responseObject, NSError *error) {
self.accessToken = responseObject[#"credentials"][#"token"];
[userDefaults setObject:self.accessToken forKey:#"accessToken"];
[userDefaults synchronize];
[self mostPopular];
}];
} else {
[self mostPopular];
}
}
- (void)tuula {
NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = [[NSString alloc]initWithFormat:#"https://api.instagram.com/v1/users/7522782/media/recent/?access_token=%#", self.accessToken];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSLog(#"links: %#", location);
NSData *data = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.photos = [responseDictionary valueForKeyPath:#"data"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
});
}];
[task resume];
}
- (void)wendyslookbook {
NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = [[NSString alloc]initWithFormat:#"https://api.instagram.com/v1/users/14454619/media/recent/?access_token=%#", self.accessToken];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSLog(#"links: %#", location);
NSData *data = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.photos = [responseDictionary valueForKeyPath:#"data"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
});
}];
[task resume];
}
- (void)mostPopular {
[self tuula];
[self wendyslookbook];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.photos count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"photo" forIndexPath:indexPath];
cell.backgroundColor = [UIColor lightGrayColor];
cell.photo = self.photos[indexPath.row];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *photo = self.photos[indexPath.row];
DetailViewController *viewController = [[DetailViewController alloc]init];
viewController.modalPresentationStyle = UIModalPresentationCustom;
viewController.transitioningDelegate = self;
viewController.photo = photo;
[self presentViewController:viewController animated:YES completion:nil];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
presentingController:(UIViewController *)presenting
sourceController:(UIViewController *)source {
return [[PresentDetailTransition alloc]init];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
return [[DismissDetailTransition alloc]init];
}
#end