从CollectionView查看项目信息到ViewController

时间:2015-05-01 15:42:59

标签: ios objective-c uicollectionview segue

下午好,

当用户触摸我的CollectionView中的某个项目时,我试图制作一个Segue,但它无法正常工作。首先,我从数据库中获取用户的条目(它们是图像的完整URL),然后我将其显示在集合视图中。

问题是,当我尝试发送我触摸过的那个时,它总是为NULL。我尝试过以下教程和示例,但没有人从数据库加载条目(也是完整的URL)。图像被加载到" fetchImages"。

你能帮助我吗?如何发送我触摸的项目的URL,我该怎么做?

这是我的ViewController(我的CollectionView所在的位置):

//

#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

提前致谢。

1 个答案:

答案 0 :(得分:0)

您必须添加此委托方法,每次在UICollectionView中选择项目时,此委托都会调用。在这个代表内部执行你的segue。作为发件人,发送您选择的indexPath。

- (void)collectionView:(UICollectionView *)collectionView 
         didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    [self performSegueWithIdentifier:@"segueentry" sender: indexPath];
}

然后从- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender开始,您可以将选定的indexPath作为逻辑的发送方。