Retrieve Image for different Class Data browser Parse.com - uiimageview

Hello everyone I'm trying to display the profile picture of a user registered with the app.
In this query I am getting data from a different class from wherever it is in the photo databrowser. I tried with MatchesQuery but I can not find the right combination ... Probably my code is wrong ...
- (void)QueryForTableView {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:#"Amicizie"];
[QueryForFriend whereKey:#"A_User" equalTo:[PFUser currentUser]];
[QueryForFriend includeKey:#"Da_User"];
PFQuery *RetrievePhoto_User = [PFUser query];
[RetrievePhoto_User whereKey:#"photo" matchesQuery:QueryForFriend];
[QueryForFriend findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"nome:%#", objects);
self.UtentiInAttesa = objects ;
[self.FFTableView reloadData];
}
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellaAmici";
FFCustomCellFriendInAttesa *cell = [self.FFTableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[FFCustomCellFriendInAttesa alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellaAmici"];
}
PFUser *FriendUser = [self.UtentiInAttesa objectAtIndex:indexPath.row];
NSString *ValueNomeCognome = [[FriendUser objectForKey:#"Da_User"] valueForKey:FF_USER_NOMECOGNOME];
cell.FFNomeFriendLabel.text = ValueNomeCognome;
cell.FFFotoProfiloInAttesa.file = [FriendUser objectForKey:#"photo"];
cell.FFFotoProfiloInAttesa.image = [UIImage imageNamed:#"FFNoFotoUSer"];
[cell.FFFotoProfiloInAttesa.layer setMasksToBounds:YES];
[cell.FFFotoProfiloInAttesa.layer setCornerRadius:22.5f];
[cell.FFFotoProfiloInAttesa loadInBackground];
return cell;
}

After a little chat with you. The following code is unnecessary and wrong. So simple remove it and you are set:
PFQuery *RetrievePhoto_User = [PFUser query];
[RetrievePhoto_User whereKey:#"photo" matchesQuery:QueryForFriend];

Related

PFQueryTableView Memory

I've been working with the PFQueryTableView with images and text. After implementing this code:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithClassName:#"Story"];
self = [super initWithCoder:aDecoder];
if (self) { // This table displays items in the Todo class
self.parseClassName = #"Story";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 25;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object {
static NSString *cellIdentifier = #"cell";
PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellIdentifier];
}
// Configure the cell to show todo item with a priority at the bottom
cell.textLabel.text = object[#"snapDetails"];
PFFile *thumbnail = [object objectForKey:#"snap"];
cell.imageView.image = [UIImage imageNamed:#"placeholder.jpg"];
cell.imageView.file = thumbnail;
return cell;
}
the log gives me this strange warning:
[/BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-
371.4/Bom/Storage/BOMStorage.c:522] is not a BOMStorage file
along with a regular memory warning. Occasionally the app also crashes and XCode displays a message that claims that it has lost connection to my iPhone. When checking the memory usage, as the table goes up or down the memory continues to increase as if the images (which are screen sized) are never released as they go off screen. Any ideas as to what can be happening?
almost in all cases, this is harmless unless your url is wrong.to make the BOMStorage file more serious, you can add this:
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Besides,you can choose other method to replace:
[image stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateNormal]

Getting reddit feed as JSON and parsing it

I'm trying to parse JSON feed from reddit.com and then display it in a tableview. The JSON looks like this:
{
kind: Listing
data: {
modhash: 3lmt2d4hq6797af804da91bde566bd067ddee68e1e7f8e0dda
children: [
{
kind: t3
data: {
domain: imgur.com
banned_by: null
media_embed: { }
subreddit: funny
selftext_html: null
selftext:
likes: null
link_flair_text: null
id: 16e9so
clicked: false
title: I left my dog unattended with the 2 year old...
num_comments: 166
score: 2213
approved_by: null
over_18: false
hidden: false
thumbnail: http://c.thumbs.redditmedia.com/DaoiOlvtdjaPBG3n.jpg
subreddit_id: t5_2qh33
edited: false
link_flair_css_class: null
author_flair_css_class: null
downs: 2481
saved: false
is_self: false
permalink: /r/funny/comments/16e9so/i_left_my_dog_unattended_with_the_2_year_old/
name: t3_16e9so
created: 1357963292
url: http://imgur.com/zGMxP
author_flair_text: null
author: ShaneNickerson
created_utc: 1357934492
media: null
num_reports: null
ups: 4694
}
...more items here
}
And here's my tableview controller code:
#import "mainRedditFunViewController.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kjsonURL [NSURL URLWithString: #"http://reddit.com/r/funny/.json"
#interface mainRedditFunViewController ()
#end
#implementation mainRedditFunViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://reddit.com/r/funny/.json"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row];
NSString *VersionString = [appsdict objectForKey:#"url"];
NSString *priceString = [appsdict objectForKey:#"author"];
NSURL *imageURL = [NSURL URLWithString:[appsdict objectForKey:#"thumbnail"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.textLabel.text = [appsdict objectForKey:#"title"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"URL: %# Author: $ %# USD",VersionString,priceString];
cell.imageView.image = imageLoad;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jsonResults count];
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
jsonResults = [json objectForKey:#"data.children"];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
However, the output is completly empty. Is there anyway I could fix it? I tried it before with another (smaller) feed and it worked fine. I'm sure if I'm doing the JSONPath formatting correctly, since I'd look like that:
-kind
->data
->children
->data (my items)
->data
->data
...
I'd appreciate any help I get!
Im sorry that this answer is late! hope that it is still needed...
I have altered your code a little bit to access the sub levels of the returned Json results.
You certainly have the right Idea but just need a few more dictionaries in your fetchedData method. If you add these dictionaries in you method underneath your NSJSONSerialization;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
//NSArray *Fullarray = [[NSArray alloc] initWithObjects:json, nil];
_jsonResult = [[NSMutableArray alloc] init];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSDictionary *chilrenDict = [dataDict objectForKey:#"children"];
for (NSDictionary *informationFromChild in chilrenDict) {
NSLog(#"chil %#", chilrenDict);
[_jsonResult addObject:chilrenDict];
}
Then in your tableView cellForRow change your appsDict to this
NSDictionary *appsdict = [[_jsonResult objectAtIndex:indexPath.row] objectForKey:#"data"];
That should fix up the code and populate the tableView...
You can run a check on this too by checking
NSLog(#"count %i", [_jsonResult count]);
Let me know if this has been of help, happy coding. T

TWRequest from a dictionary in a tableView Cell

I am trying to propagate a table view with a custom cell with the results of a TWRequest with no luck. I am trying to store the tweets in a dictionary object then calling an ObjectAtKey request and putting into a string. Here is my code - any help would be appreciated. Thanks -
-(void)fetchTweets
{
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
#"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Twitter response: %#", dict);
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *tweetText = [dict objectForKey:#"text"];
NSArray *tweetComponents = [tweetText componentsSeparatedByString:#":"];
cell.Header.text = [tweetComponents objectAtIndex:0];
cell.Details.text = [tweetComponents objectAtIndex:1];
cell.Date.text = [tweetComponents objectAtIndex:2];
return cell;
}
You will need to create an NSMutableArray of the tweets from the Twitter response.
Each tweet being a separate object.
NSMutableArray *resultArray = [[NSMutableArray] alloc] init];
for (NSDictionary *tweet in dict)
{
[resultArray addObject:tweet];
}
Then in cellForRowAtIndexPath retrieve the object based on the row of the table, something like
TweetResult *tweetResult [resultArray objectAtIndex:[indexPath row]];

Custom cells - how can I separate out tweets into componentsseparatedbyString

I have a custom cell in a tableview. All connections are made. I am conducting a Twitter search. The results of this propagate a custom cell in a tableView. I would like to separate the individual tweets out into an array using componentsseparatedbystring so that I can assign these to 4 labels in my custom cell. Any help would be greatly appreciated. Here is my code.
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"https://api.twitter.com/1/statuses/public_timeline.json"]];
NSError* error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// added this bit in
cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// THIS IS THE BIT I'M STRUGGLING WITH
// I'M GUESSING THAT THIS LINE SEPARATES THE TWEETS INTO SINGLE TWEETS?
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
// I THEN CREATE AN ARRAY TO HOLD MY COMPONENTS OF THE TWEET SO THAT I CAN SPLIT FOR MY LABELS
NSArray *arrayForCustomCell = [[NSArray alloc] init];
arrayForCustomCell = [tweet componentsSeparatedByString:#":"];
return cell;
}
You have already parsed the results in your async call. Now, you have an array of 'tweet' dictionaries and you can grab any value like this:
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *tweetText = [tweet valueForKey:#"text"];
NSString *tweetCountry = [tweet valueForKeyPath:#"place.country"] //Nested property
and then you just set your UILabels. You get the idea...

How to solve slow scrolling in UITableView - using the YouTube API

I'm working with the google YouTube API, and I'm using this code found here http://pastebin.com/vmV2c0HT
The Code that slows things down is this one here
cell.imageView.image = [UIImage imageWithData:data];
When I remove that code it scrolls smoothly. Any idea on how I can go about having it load the images from google but still scroll smoothly? I've read some of the answers on loading images in a different way, but I still can't figure out how I'll make that work with the code I'm using.
Any help will be appreciated.
Bellow is the full code.
#import "RootViewController.h"
#interface RootViewController (PrivateMethods)
- (GDataServiceGoogleYouTube *)youTubeService;
#end
#implementation RootViewController
#synthesize feed;
- (void)viewDidLoad {
NSLog(#"loading");
GDataServiceGoogleYouTube *service = [self youTubeService];
NSString *uploadsID = kGDataYouTubeUserFeedIDUploads;
NSURL *feedURL = [GDataServiceGoogleYouTube youTubeURLForUserID:#"BmcCarmen"
userFeedID:uploadsID];
[service fetchFeedWithURL:feedURL
delegate:self
didFinishSelector:#selector(request:finishedWithFeed:error:)];
[super viewDidLoad];
}
- (void)request:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedBase *)aFeed
error:(NSError *)error {
self.feed = (GDataFeedYouTubeVideo *)aFeed;
[self.tableView reloadData];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[feed entries] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0f;
}
- (void)dealloc {
[super dealloc];
}
- (GDataServiceGoogleYouTube *)youTubeService {
static GDataServiceGoogleYouTube* _service = nil;
if (!_service) {
_service = [[GDataServiceGoogleYouTube alloc] init];
[_service setShouldCacheDatedData:YES];
[_service setServiceShouldFollowNextLinks:YES];
}
// fetch unauthenticated
[_service setUserCredentialsWithUsername:nil
password:nil];
return _service;
}
#end
GCD is a wonderful thing. Here is what I do:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"youTubeCell";
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
// Load the image with an GCD block executed in another thread
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage * image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell setNeedsLayout];
});
});
dispatch_release(downloadQueue);
return cell;
}
Scrolling is now super smooth. The only drawback is that when you scroll quickly, cells are re-used and sometimes the images change as new ones come in.

Resources