Very slowly scroll on UITableView images - ios

Very slowly scroll on UITableView images.Help me please.
Did not find the right solution
My code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *const ImageCellId = #"ImageCell";
EXImageCell *cell = [tableView dequeueReusableCellWithIdentifier:ImageCellId];
RSSItem *item = [_data objectAtIndex:indexPath.row];
cell.cellTextLabel.text = item.title;
cell.cellTimeTextLabel.text = [NSDateFormatter localizedStringFromDate:item.pubDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
cell.cellAuthor.text = [NSString stringWithFormat:#"Author: %#", item.author];
NSURL *tutorialsUrl = item.link;
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
NSString *tutorialsXpathQueryString = #"//div[#class='photo']/img";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
//NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {
tutorial = [[Tutorial alloc] init];
//[newTutorials addObject:tutorial];
//tutorial.title = [[element firstChild] content];
tutorial.url = [element objectForKey:#"src"];
}
NSData *data = [NSData dataWithContentsOfURL : [NSURL URLWithString:tutorial.url]];
UIImage *imageMain = [UIImage imageWithData:data];
[cell.cellImageView setImage:imageMain];
return cell;
}
PS: dispatch_async tried to use, but to no avail

Related

Downloading JSON in iOS and using it to draw the UI

I'm relatively new to iOS development and my current project requires me to Connect to a website through a Rest API, and use JSON Objects received from the site to populate a Custom UITableViewController which I have implemented. I have been able to download the information and get it to display on the table properly, but this requires me to enter the page which starts the download, then leave the page and enter it again, upon which all of the cells are populated. How can I make my app load this information without leaving the page?
My Custom UITableViewClass contains the following methods:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *chuckFranklinConnection = #"http://chuckfranklinlaw.com/wp-json/posts?type=tribe_events";
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL: [NSURL URLWithString:chuckFranklinConnection]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error){
//Complete Data Handling from Chuckfranklinlaw.com Here
NSString *responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *e = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error: &e];
if(!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
}else {
NSLog(#"Begin Successful Parse Readout -----------");
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
}]
resume];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<##"reuseIdentifier"#> forIndexPath:indexPath];
// Configure the cell...
EventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"EventsCell"];
if(cell == nil) {
cell = [[EventTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"EventsCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//Formatting for each Cell Title
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = [[jsonArray objectAtIndex:indexPath.row] objectForKey: #"title"];
//Formatting for each Cell Detail
NSString *startDate = [[jsonArray objectAtIndex:indexPath.row] objectForKey: #"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:startDate];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
cell.data = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"ID"];
cell.detailTextLabel.text = [dateFormatter stringFromDate:date];
//Work On Implementing Image View for App in this section
NSDictionary *imageInfo = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"featured_image"];
NSDictionary *attachmentMeta = [imageInfo objectForKey:#"attachment_meta"];
NSDictionary *sizes = [attachmentMeta objectForKey:#"sizes"];
NSDictionary *thumbnail = [sizes objectForKey:#"thumbnail"];
NSString *url = [thumbnail objectForKey:#"url"];
NSLog(url);
UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
cell.imageView.image = image;
return cell;
[cell setNeedsDisplay];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showEventDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *detailView = segue.destinationViewController;
NSString *contentString = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"content"];
//The Following code mutates the HTML Strings recieved from the server into NSStrings for displaying
contentString = [contentString stringByReplacingOccurrencesOfString:#"’" withString:#"\'"];
contentString = [contentString stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
contentString = [contentString stringByReplacingOccurrencesOfString:#"</p>" withString:#"\n"];
detailView.content = contentString;
detailView.title = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString *startDate = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:startDate];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
detailView.eventTime = [dateFormatter stringFromDate:date];
//Pull Image from web and serve to next page
NSDictionary *imageInfo = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"featured_image"];
NSDictionary *attachmentMeta = [imageInfo objectForKey:#"attachment_meta"];
NSDictionary *sizes = [attachmentMeta objectForKey:#"sizes"];
NSDictionary *blogFull = [sizes objectForKey:#"blog-full"];
NSString *url = [blogFull objectForKey:#"url"];
detailView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
}
}
In your completion block: [self.tableview reloadData]. Documentation.
Actually, you will want to create a weak reference to self, then use the weak reference in your completion block.

Segue item info from CollectionView to ViewController

Good afternoon,
I'm trying to make a Segue when the user touches an item from my CollectionView, but it's not working. First, I get the entries of the user from a database (and they are the full URL of the images) and then I display it in the Collection View.
The problem is, when I try to send the one I have touched, it's always NULL. I have tried following tutorials and examples, but no one is loading the entries from a database (and the full url also). The images are loaded in the "fetchImages".
Can you help me? What do I have to do to send the URL of the item I have touched?
This is my ViewController (where my CollectionView is):
//
#import "ProfileViewController.h"
#import "CarDetailOtherViewController.h"
#import <Security/Security.h>
#import "SSKeychainQuery.h"
#import "SSKeychain.h"
#import "SBJson.h"
#interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
#end
#interface ProfileViewController ()
#end
#implementation ProfileViewController
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor: [self colorWithHexString:#"FFFFFF"]];
self.profileimage.layer.cornerRadius = self.profileimage.frame.size.width / 2;
self.profileimage.clipsToBounds = YES;
self.profileimage.layer.borderWidth = 1.0f;
self.profileimage.layer.borderColor = [UIColor whiteColor].CGColor;
[self fetchImages];
// COLLECTION VIEW
self.oneCollectionView.dataSource = self;
self.oneCollectionView.delegate = self;
}
// MOSTRAMOS LA INFO CUANDO SE HAYA MOSTRADO EL VIEW
- (void)viewDidAppear:(BOOL)animated
{
[self fetchJson];
}
// COLLECTION VIEW
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 1;
}
// COLLECTION VIEW
-(NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return 1;
}
// COLLECTION VIEW
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _carImages.count;
}
/*
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
RecipeViewCell *cell = (RecipeViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-2.png"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-selected.png"]];
return cell;
}
*/
// COLLECTION VIEW
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCollectionViewCell *myCell = [collectionView
dequeueReusableCellWithReuseIdentifier:#"MyCell"
forIndexPath:indexPath];
NSString *data = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
NSURL * imageURL = [NSURL URLWithString:data];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL: imageURL];
UIImage *img = [UIImage imageWithData:imageData];
[myCell.imageview performSelectorOnMainThread:#selector(setImage:) withObject:img waitUntilDone:YES];
});
return myCell;
}
// PROFILE INFO
-(void)fetchJson {
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSLog(#"usersPassword ==> %#", usersPassword);
NSString *post =[[NSString alloc] initWithFormat:#"usersPassword=%#",usersPassword];
//NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://website.com/profile.php"];
//NSData * data = [NSData dataWithContentsOfURL:url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSInteger stars = [(NSNumber *) [jsonData objectForKey:#"stars"] integerValue];
self.stars.text = [NSString stringWithFormat:#"%li", (long)stars];
NSInteger followers = [(NSNumber *) [jsonData objectForKey:#"followers"] integerValue];
self.followers.text = [NSString stringWithFormat:#"%li", (long)followers];
NSInteger pictures = [(NSNumber *) [jsonData objectForKey:#"photos"] integerValue];
self.pictures.text = [NSString stringWithFormat:#"%li", (long)pictures];
self.username.text = [NSString stringWithFormat:#"*%#", usersPassword];
NSString *picture = [jsonData objectForKey:#"picture"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:picture]];
self.profileimage.image = [UIImage imageWithData:imageData];
}
}
-(void)fetchImages {
self.carImages = [[NSMutableArray alloc] init];
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/posts.php?usersPassword=%#",usersPassword];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
}
NSLog(#"CARIMAGES ==> %#", _carImages);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// IMAGEN
-(UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"segueentry"])
{
NSArray *indexPaths = [self.oneCollectionView indexPathsForSelectedItems];
CarDetailOtherViewController *destViewController = segue.destinationViewController;
NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
destViewController.ID = [[_jsonArray objectAtIndex:indexPath.section] valueForKey:#"imagen"];
NSLog(#"DATA ==> %#", [[_jsonArray objectAtIndex:indexPath.section] valueForKey:#"imagen"]);
}
}
#end
Thanks in advance.
it has to be row instead of section in your prepareforsegue:
destViewController.ID = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
and btw: you can easily get the indexpath doing the following:
NSIndexPath *selectedIndexPath = [self.collectionView indexPathForCell:sender];
You have to add this delegate method, this delegate will call every time you select a item in the UICollectionView. Inside this delegate perform your segue. As the sender, send your selected indexPath.
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"segueentry" sender: indexPath];
}
Then from - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender you can get the selected indexPath as sender for your logic.

JSON Data in UITableViewCell

Hi I am developing one quizz app and the issue is, I have the following JSON Data, which is a respond from my WebService.
[
{
"id": "3",
"question": "tes!2t",
"option1": "test",
"option2": "test",
"option3": "test",
"option4": "test",
"correct_answer": "test",
"explanation": "test",
"image": "test",
"created_at": "2014-09-23 02:00:00",
"updated_at": "2014-09-09 06:19:28"
}
]
How can I display the Data option1,option2,option3 and option4 in a TableViewCell.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithFrame:CGRectZero];
}
NSString *urlString = #"http://localhost/quiz/public/questions";
NSData *JSONData = [NSData dataWithContentsOfFile:urlString:NSDataReadingMappedIfSafe error:nil];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [jsonObject objectForKey:#"questions"];
questions = [[NSMutableArray alloc] initWithCapacity:[array count]];
//choices = [[NSArray alloc] init];
for (NSDictionary *dict in array) {
question = [[Questions alloc] initWithObject:dict];
[questions addObject:question];
}
cell.textLabel.text = [choices objectAtIndex:indexPath.row];
cell.textLabel.font=[UIFont fontWithName:#"Bold" size:12];
cell.backgroundColor=[UIColor grayColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
int selectedRow = indexPath.row;
NSString *filePathChoices = [[NSBundle mainBundle] pathForResource:#"questions" ofType:#"json"];
NSData *JSONDataChoices = [NSData dataWithContentsOfFile:urlString
:NSDataReadingMappedIfSafe error:nil];
NSMutableDictionary *jsonObjectChoices = [NSJSONSerialization JSONObjectWithData:JSONDataChoices options:NSJSONReadingMutableContainers error:nil];
Any help would be appreciated. Thanks in advance !
Try this hopefully it will works:
NSString *urlString = #"your URL";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
jsonDict11 = [jsonObject valueForKey:#"question"];
NSLog(#"array %#",jsonDict11);
NSLog(#"Count : %d", [jsonDict11 count]);
Questionscount=[jsonDict11 count];
self.QuestionsText.text=[jsonDict11 objectAtIndex:ii];
In TableView:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithFrame:CGRectZero];
}
NSArray *jsonDict1=[jsonObject valueForKey:#"option1"];
NSArray *jsonDict2=[jsonObject valueForKey:#"option2"];
NSArray *jsonDict3=[jsonObject valueForKey:#"option3"];
NSArray *jsonDict4=[jsonObject valueForKey:#"option4"];
NSString *str1=[jsonDict1 objectAtIndex:ii];
NSString *str2=[jsonDict2 objectAtIndex:ii];
NSString *str3=[jsonDict3 objectAtIndex:ii];
NSString *str4=[jsonDict4 objectAtIndex:ii];
nameArr = [NSArray arrayWithObjects:str1,str2,str3,str4,nil];
cell.textLabel.text = [nameArr objectAtIndex:indexPath.row];
return cell;
}
Try this:
NSString *jsonString = #"[{\"id\":\"3\",\"question\":\"tes!2t\",\"option1\":\"test\",\"option2\":\"test\",\"option3\":\"test\",\"option4\":\"test\",\"correct_answer\":\"test\",\"explanation\":\"test\",\"image\":\"test\",\"created_at\":\"2014-09-23 02:00:00\",\"updated_at\":\"2014-09-09 06:19:28\"}]";
Pass your json string ("jsonString")
NSData *aDataJson = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *aError = nil;
NSArray *aArrJson = [NSJSONSerialization JSONObjectWithData:aDataJson options:NSJSONReadingMutableContainers error: &aError];
NSLog(#"%#",aArrJson);
NSLog(#"%#",[[aArrJson objectAtIndex:0] objectForKey:#"question"]);

in UITableView first entry and last entry switching record data when loading from server

I am developing an app that will display data from server in a parallax type UITableView, and here is my code. Everything is loading great, but cell data(image, etc) keep switching from one cell to another.
- (void)viewDidLoad
{
[self hasInternet];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self loadData];
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
[self scrollViewDidScroll:nil];
[super viewWillAppear:animated];
[self loadData];
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
- (void) loadData{
name = #"name";
email = #"email";
thumbnail = #"thumbnail";
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://URL.php"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *title_data = [dataDict objectForKey:#"fname"];
NSString *title_data2 = [dataDict objectForKey:#"lname"];
NSString *fulname = [NSString stringWithFormat:#"%# %#", title_data, title_data2];
NSString *emAil = [dataDict objectForKey:#"email"];
NSString *thumbnail_data = [dataDict objectForKey:#"img"];
thumbnail_data = [NSString stringWithFormat:#"http://URL/upload/%#",thumbnail_data];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys: fulname, name, emAil, email, thumbnail_data, thumbnail, nil];
[myObject addObject:dictionary];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"parallaxCell";
JBParallaxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[JBParallaxCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *text;
text = [NSMutableString stringWithFormat:#"%#",[tmpDict objectForKeyedSubscript:name]];
NSMutableString *mail;
mail = [NSMutableString stringWithFormat:#"%#",[tmpDict objectForKeyedSubscript:email]];
NSMutableString *images;
images = [NSMutableString stringWithFormat:#"%# ",[tmpDict objectForKey:thumbnail]];
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
cell.parallaxImage.image = [[UIImage alloc]initWithData:data];
});
});
cell.titleLabel.text = [NSString stringWithFormat:#"%#",text];
cell.subtitleLabel.text = [NSString stringWithFormat:#"%#",mail];
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSArray *visibleCells = [self.tableView visibleCells];
for (JBParallaxCell *cell in visibleCells) {
[cell cellOnTableView:self.tableView didScrollOnView:self.view];
}
}
When I compile it, it shows all my data but then keep switching from one cell to another. Any help will be appreciated. Thanks
Because UITableView reuse the cell so when you scroll down or up the previous cell which is gone from your tableview bound is reuse. but it's image view has an image when it use last time so you have to clear first the imageview.
so put this line
cell.parallaxImage.image = nil;
Before the dispatch queue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
You can use this code it will save the images in document directry and then show it.
please change the variable name.
NSString *imageURL = [[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"];
NSURL *url = [NSURL URLWithString:imageURL];
NSArray *seperate = [[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"] componentsSeparatedByString:#"/"];
NSString *fileName = [NSString stringWithFormat:#"%#.png",[seperate objectAtIndex:seperate.count-1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *getImagePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
if ([img isKindOfClass:[UIImage class]]) {
//Set Downloaded Image
[cell.matchUserImageView setImage:img];
}
else {
if ([[ValidationString sharedManager] isNullString:[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"]] == YES) {
//Set Default Image
[cell.matchUserImageView setImage:[UIImage imageNamed:#"photo_icon.png"]];
}
else{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSArray *seperate = [[[matcheListArr objectAtIndex:indexPath.row] valueForKey:#"thumbnail_image"] componentsSeparatedByString:#"/"];
NSString *fileName = [NSString stringWithFormat:#"%#.png",[seperate objectAtIndex:seperate.count-1]];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
[cell.matchUserImageView setImage:[UIImage imageWithData:imageData]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
[imageData writeToFile:savedImagePath atomically:NO];
});
});
}
}

NSInvalidArgumentException reason: data parameter is nil in UITableView while trying to display the Flickr images

Hi in my application I want to display the Flickr album list in UITableView so i have searched for long time and i have found some solution. I have used the method which given in the solution its not working its giving error like
NSInvalidArgumentException', reason: 'data parameter is nil
The solution link click here
And since I'm trying this for first time I'm not able resolve this issue. This is MY API LINK for Flickr
I have used this code to display the Flickr image Album list in UItableview
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoid1;
}
My Flickr API key
#define FlickrAPIKey #"a6a0c7d5efccffc285b0fe5ee1d938e3"
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoid1 = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
}
My TableView code
- (void)loadFlickrPhotos
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=%#&user_id=%#&per_page=10&format=json&nojsoncallback=1", FlickrAPIKey, #"124757153#N04"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *photoid = [photoset objectForKey:#"id"];
[photoid1 addObject:photoid];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [photoSetNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier =#"Cell";
flickrpoliticalCell *cell =(flickrpoliticalCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[flickrpoliticalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.tit.text = [photoSetNames objectAtIndex:indexPath.row];
return cell;
}
try this
- (void)loadFlickrPhotos
{
//
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&format=json&user_id=124757153#N04&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}

Resources