使用url iOS目标c追加数组

时间:2017-06-13 04:50:00

标签: ios objective-c xcode uicollectionview

我有一个基本网址,我在服务器中提取的数组中有图像名称。我正在使用集合视图,我必须在集合视图中显示所有23个图像我有两个问题

  1. 当我尝试访问cell.imageview.image时,它说单元格中没有属性图像视图,但在自定义cell.h文件中我创建了插座,我使用的是故事板
  2. 2.其中一个是字符串基本URL和从服务器john中提取的数组中图像的其他结束路径或文件名

    这是我从数据中得到的 -

        {
        "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;
    }
    

    这是nslog的服务器回复

    这是我存储数据的数组的难点

    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"
    

    我有一个基本网址如何在集合视图中获取所有这些图片?

    这是customcell.h文件

    #import <UIKit/UIKit.h>
    
    @interface CustomCell : UICollectionViewCell
    
    
    @property (strong, nonatomic) IBOutlet UIImageView *imageView;
    @property (strong, nonatomic) IBOutlet UILabel *lbl;
    
    
    
    @end
    

    customcell.h文件

    #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
    

    查看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;
    
    
    }
    

2 个答案:

答案 0 :(得分:0)

    NSString *path = [NSString stringWithFormat:@"%@/%@", baseUrl, imageName];
    NSURL *url = [NSURL URLWithString:path];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *imgage = [[UIImage alloc] initWithData:data];

将此图片传递给您的imageview。 在从服务器加载图像时,您还可以使用SDWebImage进行图像缓存。 https://github.com/rs/SDWebImage

答案 1 :(得分:0)

viewDidLoad方法

中注册自定义单元格
[yourCollectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:@"your Cell Identifier"];

然后你会写cellForItemAtIndexPath方法

-(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;
}
  

下载SDWebimageImageLoader以使用具有缓存支持的异步映像下载程序。