My viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
appdataModel = [AppDataModel getInstance];
appdataModel.newsApiUrl = homePagesUrl;
self.view.backgroundColor = [UIColor whiteColor];
NSString *path = [[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"plist"];
contactsArray = [NSArray arrayWithContentsOfFile :path];
[self GetHomePageData];
/**** for left side menu ***/
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sideBarButton setTarget: self.revealViewController];
[self.sideBarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
i am getting data from this method :
-(void)GetHomePageData{
// url_to_load = homePagesNews;
NSString *urlString = [NSString stringWithFormat:#"%#",newsApiUrl];
NSURL *url = [[NSURL alloc]initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
}
for show data in UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier =#"Cell";
CustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
details = res[indexPath.row];
NSString *titleNews = details[#"title"];
NSString *newsDateTime = details[#"datetime"];
NSString *NewsImageName = details[#"featured_image"];
//UIImage *image = [UIImage imageNamed:NewsImageName ];
// UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:NewsImageName]]];
customCell.customFirstNameLabel.text = titleNews;
customCell.customLastnameLabel.text = newsDateTime;
//customCell.customImageView.image =image;
NSURL *imageUrl=[details valueForKey:#"featured_image"];
[customCell.customImageView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:#"no_image.png"]];
//[tableView reloadData];
return customCell;
}
for show detils data in a tableview after select a cell
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"detailSegue"]) {
//s NSIndexPath *path = Nil;
NSString *titleString = Nil;
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
titleString = [res objectAtIndex:path.row];
[[segue destinationViewController] setTitle:titleString];
}
}
But it's now working . can some help me to solve this ..Thanks in advance
NSString *NewsImageName = details[#"featured_image"]; ,it is dictionary not a string!, you could delete that line.
[details valueForKey:#"featured_image"] it is string, but you are assigning it to NSURL directly.
NSURL *imageUrl=[details valueForKey:#"featured_image"];
replace it as follows
NSURL* imageUrl= [NSURL URLWithString:[details valueForKey:#"featured_image"]];
Related
I have a base url and I have the image names in a array extracted from there server .I am using a collection view, I have to display all the 23 images in the collection view I have two problems
when I try to access cell.imageview.image it says no property image view in cell but in custom cell.h file I have created the outlet and I am using storyboard
2.as one is string base url and other end path or filename of the images in array extracted from john from server
this is how I get from data--
{
"added_by" = 1;
"category_id" = 182;
"category_image" = "shots.png";
"category_name" = Shots;
sequance = 19;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 168;
"category_image" = "classiccocktail.png";
"category_name" = "Classic Cocktails";
sequance = 20;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 167;
"category_image" = "sprit.png";
"category_name" = "Non Alcoholic Bevereges";
sequance = 21;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 162;
"category_image" = "nonalcoholic.png";
"category_name" = "Non Alcoholic Coolers";
sequance = 22;
status = 0;
"store_id" = 1;
}
this is nslog of server reply
This is the slog of the array in which I have stored the data
2017-06-13 10:16:39.181 MenuBar[1703:94836] (
"kinfisherultra.png",
"impotedbeernew.png",
"blendedwhiskyne.png",
"johywalkerbluee.png",
"singlemaltnew.png",
"americanwishkynew.png",
"irishwishkynew.png",
"Belvedere-Vodka.png",
"Ginnew.png",
"Tequilanew.png",
"rumnew.png",
"amarula.png",
"aprities.png",
"breezernew1.png",
"conganbrndynew.png",
"wine&sparkling.png",
"bottels.png",
"cocktailpitchers.png",
"mocktails.png",
"shots.png",
"classiccocktail.png",
"sprit.png",
"nonalcoholic.png"
)
and I have a base url how to get all these images in collection view?
this is customcell.h file
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *lbl;
#end
customcell.h file
#import "CustomCell.h"
#implementation CustomCell
-(void)awakeFromNib {
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[self addGestureRecognizer:tap];
[super awakeFromNib];
}
-(void)onButtonTapped:(id)sender
{
//the response to the gesture.
//mind that this is done in the cell. If you don't want things to happen from this cell.
//then you can still activate this the way you did in your question.
}
#end
view controller.hfile
if(!sharedSessionMainQueue){
sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
}
[[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSDictionary *temp=jsonDict;
NSLog(#"Req cust:%#",requestReply);
NSLog(#"requestReply cust liqour category: %#", jsonDict);
NSArray *imgNameArray = [temp valueForKey: #"category_name"];
NSLog(#"$$$%#$$$",imgNameArray);
self.iname=[jsonDict valueForKey:#"category_image"];
NSLog(#"%#",self.iname);
//[self imagedl];
NSDictionary *tempz=[jsonDict valueForKey:#"category_name"];
Photos = [NSArray arrayWithObjects:#"http://test.kre8tives.com/barebones/upload/%#",self.iname, nil];
NSLog(#"^^^%#",tempz);
//NSLog(#"$$%#",[Photos objectAtIndex:]); //Here can show Img's values correctl
// }
// self.recipeImageView.image = [UIImage imageNamed:self.recipeImageName];
}] resume];
_barbutton.target = self.revealViewController;
_barbutton.action = #selector(revealToggle:);
//[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)geti{
NSString *temps= [NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/%#",self.iname];
UIImage *temp;
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:temps]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
//temp.image= [UIImage imageWithData:data];
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 23;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//[CustomCell registerClass:[CustomCell class] forCellWithReuseIdentifier:reuseIdentifier];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
[[[cell contentView] subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
UIView * contents=[[UIView alloc] initWithFrame:cell.contentView.bounds];
[contents setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:contents];
_imageView.image;
// set tag to the indexPath.row so we can access it later
[cell setTag:indexPath.row];
// add interactivity
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[cell addGestureRecognizer:tap];
NSString *fileName = [NSString stringWithFormat:#"%#",self.iname]; //objectAtIndex:indexPath];
NSLog(#"%#",fileName);
NSString *baseurl=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSDictionary *doors = [NSMutableArray new];
NSString *base=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSLog(#"%#",doors);
NSString *path = [NSString stringWithFormat:#"%#/%#", baseurl, _iname];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
//NSString *filePath = [baseurl stringByAppendingPathComponent:fileName];
NSDictionary *dict = self.iname[indexPath.row];
NSLog(#"%#", [self.iname objectAtIndex: indexPath.row]);
NSString *filePath=[NSString stringWithFormat:#"%#%#",baseurl,fileName];
NSString *paths = [NSString stringWithFormat:#"%#/%#", baseurl, [[dict valueForKey:#"category_image"] objectAtIndex: indexPath.row]];
NSLog(#"%#",dict);
NSString *temps= [NSString stringWithFormat:#"%#",filePath];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:paths]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
UIImage *imgage = [[UIImage alloc] initWithData:data];
_imageView.image=[[UIImage alloc] initWithData:imgage];
_imageView.image=[[NSData alloc]initWithData:data];
//imageView.contentMode = UIViewContentModeScaleAspectFill;
// _imageView.clipsToBounds = YES;
//imageView.tag = IMAGE_VIEW_TAG;
}];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
Register your custom cell in viewDidLoad method
[yourCollectionView registerNib:[UINib nibWithNibName:#"CustomCell" bundle:nil] forCellWithReuseIdentifier:#"your Cell Identifier"];
And then you will write on cellForItemAtIndexPath method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"your Cell Identifier";
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSDictionary *dict = imageAry[indexPath.row];
//SdWebimage to load image
[cell.imgUser sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", baseUrl, dict[#"imageName"]]];
return cell;
}
Download SDWebimageImageLoader to use of async image downloader with cache support.
NSString *path = [NSString stringWithFormat:#"%#/%#", baseUrl, imageName];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
pass this image to your imageview.
As you are loading images from server, you can also use SDWebImage for image caching purpose.
https://github.com/rs/SDWebImage
i'm displaying data from a webservice in my tableview app but i get the array twice in the tableview.
also i'm trying to use the endless scroll to show paginated data without success
(void)viewDidLoad {
[super viewDidLoad];
self.articlesArray = [[NSMutableArray alloc] init];
[self fetchData:1];
}
my function to fetch data
-(void) fetchData:(int)page {
NSString *urlString = [NSString
stringWithFormat:#"http://url?page=%d", (int)page];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
self.articlesArray = [NSJSONSerialization JSONObjectWithData:theData
options:NSJSONReadingMutableContainers
error:nil];
[self.tableView registerNib:[UINib nibWithNibName:#"ArticleCell" bundle:nil] forCellReuseIdentifier:#"ArticleCell"];
}
and here's my tableview methods please see what i did wrong
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0)
{
return [self.articlesArray count];
else
return [self.articlesArray count];
}
// return [self.articlesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
if (3 == (row % 4)) { // or 0 == if you want the first cell to be an ad!
static NSString *MyIdentifier = #"AdCell";
AdViewCell *cell = (AdViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if ((cell == nil) || (![cell isKindOfClass: AdViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AdCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell = [[AdViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
GADBannerView *bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
bannerView.adUnitID =#"";
bannerView.rootViewController =self;
GADRequest *request = [GADRequest request];
[bannerView loadRequest:request];
[cell.contentView addSubview:bannerView];
return cell;
}
else{
static NSString *simpleTableIdentifier = #"ArticleCell";
ArticleViewCell *cell = (ArticleViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if ((cell == nil) || (![cell isKindOfClass: ArticleViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ArticleCell" owner:self options:nil];
cell = [nib objectAtIndex:1];
cell = [[ArticleViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier] ;
}
NSDictionary * tempDictionary = [self.articlesArray objectAtIndex:indexPath.row];
NSString *imageUrl = [[self.articlesArray objectAtIndex:indexPath.row]objectForKey:#"featured_image"];
imageUrl = [imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl ] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image){
// Set your image over here
}else{
//something went wrong
NSLog(#"Error occured : %#", [error description]);
}
}];
NSString * title=[tempDictionary valueForKeyPath:#"title.rendered"];
cell.titleLabel.text = title;
return cell;
}
}
You can remove duplicate values once you get response from json, before reload tableview remove duplicate elements from array
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:YourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
Thanks
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.
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];
});
});
}
}
Everytime I start scrolling in the tableView the subtitleLabel text keeps overlapping each other in every row. I've tried for the last 4 hours every single search on the Internet for this problem I have clicked and tried.
Here is my ViewController.m:
#interface ANViewController()
{
NSMutableArray *TitleLabel;
NSMutableArray *SubtitleLabel;
NSMutableArray *AvatarImages;
}
#end
#implementation ANViewController
#synthesize thetableview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.thetableview.delegate = self;
self.thetableview.dataSource = self;
TitleLabel = [NSMutableArray array];
SubtitleLabel = [NSMutableArray array];
AvatarImages = [NSMutableArray array];
__block NSArray *posts;
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSError *error;
NSMutableDictionary *allNews = [NSJSONSerialization JSONObjectWithData:allNewsData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
posts = allNews[#"data"];
for (NSDictionary *newsPost in posts) {
[TitleLabel addObject:newsPost[#"title"]];
[SubtitleLabel addObject:newsPost[#"post_message"]];
NSString *avatarUrl = AVATAR_URL;
NSString *avatarExt = #".jpg";
[AvatarImages addObject:[NSString stringWithFormat:#"%#%#%#", avatarUrl, newsPost[#"user_id"], avatarExt]];
}
}
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
long count = TitleLabel.count;
if(count == 0){
count = 1;
}
return count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier;
ANTableViewCell *Cell;
if(TitleLabel.count == 0){
NSLog(#"Did with no news");
CellIdentifier = #"Cell_NoNews";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.noNewsLabel.text = #"No news to display!";
}else{
NSLog(#"Did with news");
CellIdentifier = #"Cell";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.TitleLabel.text = [TitleLabel objectAtIndex:indexPath.row];
Cell.SubtitleLabel.text = [SubtitleLabel objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[AvatarImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
Cell.AvatarImage.image = img;
}
return Cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Just change UITableViewCellStyleSubtitle for UITableViewCellStyleDefault, and you need an asynchronous connection instead of a synchronous like you're doing: NSData *allNewsData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:API_URL]]; in your viewDidLoad method that is blocking your main thread.
You can adapt this code to your need, in order to download it on the background:
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});