简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM