2015-05-01 52 views
0

下午好,Segue公司項目信息到視圖控制器

我試圖做一個Segue公司當用戶觸摸從我的CollectionView的項目,但它不工作。首先,我從數據庫中獲取用戶的條目(並且它們是圖像的完整URL),然後將其顯示在「集合視圖」中。

問題是,當我嘗試發送我碰到的那個時,它總是空的。我已經嘗試了以下教程和示例,但是沒有人正在從數據庫加載條目(還有完整的url)。圖像加載在「fetchImages」中。

你能幫我嗎?我需要做些什麼才能發送我碰過的物品的網址?

這是我的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 

在此先感謝。

+0

您需要縮小爲什麼數據爲零。在prepareForSegue中,你應該確定indexPaths,indexPath,_jsonArray或_jasonArray [indexPath.section]中的任何一個是否爲零。 – rdelmar

回答

0

它必須是行,而不是部分在prepareforsegue:

destViewController.ID = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:@"imagen"]; 

,並順便說一句:你可以很容易地得到indexpath執行以下操作:

NSIndexPath *selectedIndexPath = [self.collectionView indexPathForCell:sender]; 
+0

它的工作,感謝您的解決方案和技巧:) – BBangF1

+0

不客氣:) –

0

你必須添加這個委託方法,這個委託會每次在UICollectionView中選擇一個項目時調用。在這個代表內部執行你的繼續。作爲發件人,發送您選擇的indexPath。

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

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

然後從- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender你可以選擇indexPath發件人爲你的邏輯。

相關問題