I have a NSDictionary called itemDict and when printing
NSLog(#"itemDictValues:%#",itemDict);
The output is in this format:
itemDictValues:
GTLPlusPerson 0xab821e0:
{etag:""LTv_6IJISeUQGTVXLjMeOtebkoM/eup2crXcelmpMFKesXWlGkJjCiE"" kind:"plus#person" id:"1145282979128841" objectType:"person" displayName:"FirstName LastName" image:{url} url:"https://plus.google.com/1145282979128841"}
From this I need to extract the values corresponding to id, displayName and url to my NSString variables, in this format
profileId=1145282979128841;
Name=FirstName LastName;
Profilepic=https://plus.google.com/1145282979128841;
How do I go about this?
try this ...
_profileId=(NSString*)((GTLPlusPerson*)itemDict).identifier;
_profileName= (NSString*)((GTLPlusPerson*)itemDict).displayName;
_profileImageURLPath=(NSString*)((GTLPlusPerson*)itemDict).image.url;
You just parse the Dictionary to get your desired information.
NSString *profileId = [itemDict objectForKey:#"id"];
NSString *displayName = [itemDict objectForKey:#"displayName"];
Now that image, I think that's in a dictionary itself. And since you haven't specified what's inside that dictionary, so here's what I think you should do:
NSDictionary *imageDict = [itemDict objectForKey:#"image"];
NSURL *imageURL = [imageDict objectForKey:#"url"];
Then getting the UIImage becomes pretty straightforward :
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:imageURL];
NSData *imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
UIImage *image = [[UIImage alloc] initWithData:imageData];
You should choose the sendAsynchronousRequest method as it happens in the background and doesn't hold up the functionality of your app.
For an NSDictionary
NSString *profileId = itemDict[#"id"]
NSString *name = itemDict[#"displayName"]
NSString *profilePic = itemDict[#"image"][#"url"]
If it is GTLPlusPerson object then access the properties with objective-c dot syntax
NSString *profileId = itemDict.id;
NSString *name = itemDict.displayName;
NSString *profilePic = itemDict.url;
Judging by your log, it appears it is a GTLPlusPerson object and not an NSDictionary
NSArray* peopleList = peopleFeed.items;
NSLog(#"peopleList %# ",peopleList.description);
for (NSArray *dict in peopleFeed.items) {
NSString *peopleStrID=(NSString*)((GTLPlusPerson*)dict).identifier;
NSLog(#"peopleStrID %#",peopleStrID);
NSString *peopleName = (NSString*)((GTLPlusPerson*)dict).displayName;
NSString *peoplePic = (NSString*)((GTLPlusPerson*)dict).image.url;
}
The easiest way is to use the code Google provides:
if ([[GPPSignIn sharedInstance] authentication]) {
// The user is signed in.
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:#"me"];
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
plusService.retryEnabled = YES;
//auth = GTMOAuth2Authentication object from login
[plusService setAuthorizer:auth];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPerson *person,
NSError *error) {
if (error) {
GTMLoggerError(#"Error: %#", error);
} else {
// Retrieve the display name and "about me" text
NSString *description = [NSString stringWithFormat:#"%#\n%#", person.displayName, person.aboutMe];
NSString *imageURL = person.image.url;
}
}];
} else {
//user is logged out
}
}
Related
Good afternoon,
I have an app that asks the user to log in thanks to twitter's doc found there: Log in with twitter. Then, I can successfully load the user's timeline. This timeline loads in a NavigationController which has the interface TWTRTimelineViewController. Now, I would like that when one user holds his finger on a tweet, or just click on one tweet, rather than opening Safari to display it, it pops up a button where I'll be able to work on the tweet after clicking. I will need to get access to the text and the image of the tweet.
From my understanding, I will need to delegate all the tweets to some kind of TWTRTweetView controller to work on them but I'm not so sure how, since I'm completely new to this. I did try to read the doc but couldn't really get it, and most of the example are written in Swift. I'm also not sure how I'm supposed to access the tweet's properties. I have tried STTwitter where I played with some JSON formatted texts and where I was able to get the text and the image URL but I can't figure out how to do so directly with TwitterKit. Here's my actual code of the controller that display the timeline:
#import "TwitterTimelineViewController.h"
#import <TwitterKit/TwitterKit.h>
#import "AppDelegate.h"
#interface TwitterTimelineViewController ()
#property (strong, nonatomic) IBOutlet UITableView *TwitterTableView;
#end
#implementation TwitterTimelineViewController
TWTRUserTimelineDataSource *userTimelineDataSource;
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
[[Twitter sharedInstance] startWithConsumerKey:#"myConsumerKey" consumerSecret:#"myConsumerSecretKey"];
TWTRAPIClient *APIClient = [[TWTRAPIClient alloc] init];
userTimelineDataSource = [[TWTRUserTimelineDataSource alloc] initWithScreenName:delegate.twitterUsername APIClient:APIClient];
self.dataSource = userTimelineDataSource;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
return [[Twitter sharedInstance] application:app openURL:url options:options];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Any help would be awesome!
Cheers,
Theo.
Found the answer myself. For anyone struggling with the same issue, here the code I wrote. A bit messy but it works.
-(IBAction)ShowTweets: (id) sender{
UIButton *clicked = (UIButton *) sender;
NSString *tweetToDecryptIndex = [NSString stringWithFormat: #"%ld", (long)clicked.tag];
//gets all tweets from current timeline
NSArray *allTweets = self.snapshotTweets;
//look the tweets, get the URL and removes it to get the text only
NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
//gets the single tweet from clicked button
TWTRTweet *tweet = [allTweets objectAtIndex:(long)clicked.tag];
NSString *content = tweet.text; //gets the text
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:content options:0 range:NSMakeRange(0, [content length])]; //find the URL
NSURL *url; //contains the url from the text of the tweet
NSString *ciph; //text from tweet without the url
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
url = [match URL];
ciph = [content substringToIndex:content.length-url.absoluteString.length];
}
}
//Now, ask a JSON answer from twitter of the specific tweet using its ID
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/statuses/show.json";
NSDictionary *params = #{#"id" : tweet.tweetID};
NSError *clientError;
NSURLRequest *request = [client URLRequestWithMethod:#"GET" URL:statusesShowEndpoint parameters:params error:&clientError];
if (request) {
[client sendTwitterRequest:request completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
//NSLog(#"%#", json);
//looking for the media_url
NSString *media = [json valueForKeyPath:#"entities.media"];
NSArray *urlArray = [media valueForKey:#"media_url_https"];
//finally getting the url as a string
NSMutableString * urlOfImageString = [[NSMutableString alloc] init];
for (NSObject * obj in urlArray)
{
[urlOfImageString appendString:[obj description]];
}
//NSLog(#"%#",urlOfImageString);
//constructing name for image to write in path
NSString *tweetID = tweet.tweetID;
NSString *imgName = [tweetID stringByAppendingString:#".jpg"];
NSString *tmp = [#"/your/path" stringByAppendingString:imgName];
//NSLog(#"%#", tmp);
//Now writting the image
NSURL *urlOfImageUrl = [NSURL URLWithString:urlOfImageString];
NSData *imageData = [NSData dataWithContentsOfURL:urlOfImageUrl];
}
else {
NSLog(#"Error: %#", connectionError);
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSString *urlString = [pictureURL absoluteString];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSString *urlString = [pictureURL absoluteString];
NSLog(#"sting=%#",urlString);
PFUser *me = [PFUser currentUser];
me[#"facebookId"] = userData[#"id"];
me["pictureURL"] = userData[urlString];
me[#"username"] = userData[#"name"];
[me saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if (error) {
NSLog(#"Error to store=%#",error.localizedDescription);
}
}];
[self presentViewController:push animated:YES completion:nil];
} else {
[self presentViewController:push animated:YES completion:nil];
}
}];
I need to store the Facebook Image or URL when any new user login into my app. AFAIK we can't save the url directly so tried to convert it into NSString but then it threw error "'Can't use nil for keys or values on PFObject. Use NSNull for values.'"
Is there any way so that I can store that link or any other alternate way to save directly the Image into Parse?
Your issue is most likely being caused by the following line:
me["pictureURL"] = userData[urlString];
You most likely want this to be:
me["pictureURL"] = urlString;
As you have it, you will setting me[#"pictureURL"] to nil because you probably don't have a value in userData with a key matching urlString.
Try this, the url should be converted to data then saved as a PFFile.
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture? type=large&return_ssl_resources=1", facebookID]];
NSData *data = [NSData contentsOfURL:picureURL];
PFFile *file = [PFFile fileWithData:data];
//save it
[file saveInBackground];
Hope that helps!
I'm stuck with an issue on how to best load a couple of UILabels asynchronously.
Here is my cellForRowAtIndexPath method:
UPDATE:
Based on the answer below, I've made changes:
Here is my new cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Retrieve cell
NSString *cellIdentifier = #"BuildingItem";
BuildingsTableViewCell *cell = [[tableView dequeueReusableCellWithIdentifier:cellIdentifier] initWithFrame:CGRectMake(10, 10,580, 100)];
// Get the area to be shown
Buildings *item = _feedItems[indexPath.row];
NSURL *MyURL = [NSURL URLWithString:item.buildingPointerImage];
UIImage *placeholder = [UIImage imageNamed:#"placeholder"];
NSString *path = [MyURL absoluteString];
NSString *key = [path MD5Hash];
[cell.buildingImageView loadImageFromURL:(NSURL*)MyURL placeholderImage:(UIImage*)placeholder cachingKey:(NSString*)key];
cell.buildingName.text = item.buildingPointerName;
cell.buildingYear.text = item.buildingPointerYear;
NSString *URL = #"http://rets.miamiresidential.com/ios/condos/buildings.php?action=get_range";
NSString *streetNumberURL = [NSString stringWithFormat:#"&street_number=%#",item.buildingStreetNumber];
NSString *streetNameURL = [NSString stringWithFormat:#"&street_name=%#",item.buildingStreetName];
NSString *ZipcodeURL = [NSString stringWithFormat:#"&zipcode=%#",item.buildingZipcode];
NSString *P1 = [URL stringByAppendingString:streetNumberURL];
NSString *P2 = [P1 stringByAppendingString:streetNameURL];
NSString *P3 = [P2 stringByAppendingString:ZipcodeURL];
NSURL *jsonFileUrl = [NSURL URLWithString:P3];
NSLog(#"%#",P3);
[cell.buildingSalesRange loadSalesRangeFromURL:(NSURL*)jsonFileUrl];
[cell.buildingRentalsRange loadRentalsRangeFromURL:(NSURL*)jsonFileUrl];
cell.layer.borderColor = [[UIColor whiteColor]CGColor];
cell.layer.backgroundColor = [[UIColor clearColor]CGColor];
cell.layer.borderWidth = 2;
return cell;
}
and here is my new .m file:
#import "PriceRanges.h"
#import <objc/runtime.h>
#implementation UILabel(Prices)
-(void) loadSalesRangeFromURL:(NSURL*)url {
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyStyle setLocale:locale];
[currencyStyle setMaximumFractionDigits:0];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
NSLog(#"Error,%#", [error localizedDescription]);
}
else
{
NSArray *priceArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSNumber *number = [priceArray valueForKeyPath:#"sales.number"];
NSString *lowest = [priceArray valueForKeyPath:#"sales.lowest"];
NSDecimalNumber *lowestDecimal = [NSDecimalNumber decimalNumberWithString:lowest];
NSString *lowestPrice = [currencyStyle stringFromNumber:lowestDecimal];
if (![number isEqualToNumber:[NSNumber numberWithInt:0]]) {
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *labelFromData = [[UILabel alloc] init];
[labelFromData setText:[NSString stringWithFormat:#"%# for Sale from %#",number,lowestPrice]];
if (labelFromData) {
if ([self.text isEqualToString:labelFromData.text]) {
} else {
dispatch_async(dispatch_get_main_queue(), ^{
self.text = labelFromData.text;
});
}
}
self.text = [NSString stringWithFormat:#"%# for Sale from %#",number,lowestPrice];
});
}
};
}];
}
-(void) loadRentalsRangeFromURL:(NSURL*)url {
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyStyle setLocale:locale];
[currencyStyle setMaximumFractionDigits:0];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
NSLog(#"Error,%#", [error localizedDescription]);
}
else
{
NSArray *priceArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSNumber *number = [priceArray valueForKeyPath:#"rentals.number"];
NSString *lowest = [priceArray valueForKeyPath:#"rentals.lowest"];
NSDecimalNumber *lowestDecimal = [NSDecimalNumber decimalNumberWithString:lowest];
NSString *lowestPrice = [currencyStyle stringFromNumber:lowestDecimal];
if (![number isEqualToNumber:[NSNumber numberWithInt:0]]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setText:[NSString stringWithFormat:#"%# for Rent from %#",number,lowestPrice]];
});
}
}
}];
}
#end
As you might see, I have two different methods, but both still send the async request everytime the tables are scrolled.
I guess I am not clear on what to do now?
That's the problem with not having a data model independent of your UI, and a good example of when Model-View-Controller makes sense. You'll need another layer (preferably a separate class) responsible for keeping all the data you've fetched from the network, deciding when it's old enough to discard, etc. The cells should populate themselves from the cached data that the Model keeps, and if the data's not yet present, the model fetches it asynchronously and then notifies the View Controller when the new data arrive. If the cells are still visible, they get populated. If they've scrolled offscreen, been reused, etc, then the data updates don't result in any immediate UI change.
I'm trying to retrieve some text from a file that I uploaded to Parse, but anything that I try seems not to work. I tried using the example that Parse gave, but I couldn't make it work. Can somebody help or explain to me how I can do that?
This is the example:
PFFile *applicantResume = anotherApplication[#"applicantResumeFile"];
NSData *resumeData = [applicantResume getData];
Thanks
You need to convert the data back to a string, try this.
Save
PFObject * anotherApplication = [[PFObject alloc] initWithClassName:#"Resumes"];
NSData *data = [#"Working at Parse is great!" dataUsingEncoding:NSUTF8StringEncoding];
PFFile *file = [PFFile fileWithName:#"resume.txt" data:data];
anotherApplication[#"applicantResumeFile"] = file;
[anotherApplication save];
Open
[anotherApplication fetchIfNeeded];
PFFile *applicantResume = anotherApplication[#"applicantResumeFile"];
NSData *resumeData = [applicantResume getData];
NSString* dataStr = [[NSString alloc] initWithData:resumeData encoding:NSUTF8StringEncoding];
NSLog(#"Received string: %#", dataStr);
Don't forget that in practice, it's best to use 'getDataInBackgroundWithBlock:' , 'saveInBackgroundWithBlock:' , and 'fetchIfNeededInBackgroundWithBlock:'
A note on blocks:
NSLog(#"Will Run 1st: %#", reflex.description); // will be null
[applicantResume getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
reflex.description = dataStr;
NSLog(#"Will Run 3rd: %#", reflex.description); // will contain string.
}];
NSLog(#"Will Run 2nd: %#", reflex.description); // will be null
PFFile *applicantResume = object[#"applicantResumeFile"];
NSData *resumeData = [applicantResume getData];
NSString* dataStr = [[NSString alloc] initWithData:resumeData encoding:NSUTF8StringEncoding];
reflex.description = dataStr;
It workы
When I use getData it doesnt
PFFile *applicantResume = object[#"applicantResumeFile"];
[applicantResume getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
reflex.description = dataStr;
}
}];
In my iOS app I've to parse a JSON file. From this JSON I need the following stuff: name, image width and image height. To get image name I'ven't any problem, to get image with and height I use the following code:
- (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name {
NSURL* url = [NSURL URLWithString:urlImg];
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *authCredentials =#"reply:reply";
NSString *authValue = [NSString stringWithFormat:#"Basic %#",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
imageWidth = image.size.width;
imageHeight = image.size.height;
imgWidth = [NSString stringWithFormat:#"%f", imageWidth];
imgHeight = [NSString stringWithFormat:#"%f", imageHeight];
self.dictWithDataForPSCollectionView = #{#"title": name,
#"width": imgWidth,
#"height": imgHeight};
[self.arrayWithData addObject:self.dictWithDataForPSCollectionView];
NSLog(#"DATA ARRAY: %#", self.arrayWithData);
} else {
NSLog(#"ERRORE: %#", error);
}
}];
}
You can see that I save the name, image width and image height in a NSDictionary then I put this in an NSMutableArray. When it execute the NSLog, I see this:
DATA ARRAY: (
{
height = "512.000000";
title = "Eau de Toilet";
width = "320.000000";
},
{
height = "1049.000000";
title = "Eau de Toilet";
width = "1405.000000";
}
)
My question is how to get this information back in the class who call my json parser, I tried to access to the variable in this way:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
recivedData = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[recivedData appendData:data];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:recivedData options:NSJSONReadingMutableLeaves error:&err];
JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
[reader parseJson:json];
}
But when I run the code it shows me an empty array. How I can have the information in this class?
UPDATE:
The JSON I've to parse is the following:
{
"1":{
"entity_id":"1",
"type_id":"simple",
"sku":"EAU_DE_TOILET_1",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/p\/r\/product_100ml.png"
},
"2":{
"entity_id":"2",
"type_id":"simple",
"sku":"EAU_DE_TOILET_2",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/s\/c\/scheda_non_shop.jpg"
}
}
My method parseJson do the following:
- (void)parseJson:(NSDictionary *)jsonDict {
// Controllo che il json sia stato ricevuto
if (jsonDict) {
self.nameArray = [[NSMutableArray alloc]init];
self.imgUrlArray = [[NSMutableArray alloc]init];
self.dictWithDataForPSCollectionView = [[NSDictionary alloc]init];
self.arrayWithData = [[NSMutableArray alloc]init];
[self createArrayWithJson:jsonDict andIndex:1];
[self createArrayWithJson:jsonDict andIndex:2];
}
- (void)createArrayWithJson:(NSDictionary*)json andIndex:(NSString*)i {
NSDictionary *products = [json objectForKey:i];
NSString *name = [products objectForKey:#"name"];
NSString *imgUrl = [products objectForKey:#"image_url"];
// Scarico l'immagine e calcolo le dimensioni
if (name != nil && imgUrl != nil) {
[self loadImageFromWeb:imgUrl forName:name];
}
}
I hope you understand what I did
what happen is that your class is make before that your json is download, for have a good sequence you have to call your method for parse the json inside the completionHandler block, when you are sure that it is download. then when you have your object load you can parse it like this example:
for (NSDictionary *dic in reader.arrayWithData){
NSLog("height: %#",[dic objectForKey:#"height"]);
NSLog("title: %#",[dic objectForKey:#"title"]);
NSLog("width: %#",[dic objectForKey:#"width"]);
}