使用 url iOS 目标 c 附加数组

Posted

技术标签:

【中文标题】使用 url iOS 目标 c 附加数组【英文标题】:appending array with url iOS objective c 【发布时间】:2017-06-13 04:50:00 【问题描述】:

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

    当我尝试访问 cell.imageview.image 时,它​​显示单元格中没有属性图像视图,但在自定义 cell.h 文件中,我已经创建了插座并且我正在使用情节提要

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

这是我存储数据的数组的 slog

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

查看控制器.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;



【问题讨论】:

你注册自定义单元格了吗??.. 自定义单元格的类是否设置为Interface Builder中的自定义类? @Coder 如果您使用情节提要,则根本不需要注册单元格。 是的,我已将它提供给类中的自定义单元格并在自定义 cell.h 中创建,但是当我尝试 cell.imageview 时,它没有找到任何属性错误 @Vadian 如果您使用的是自定义单元格,那么我想您需要重新注册单元格 @Akshay - 显示您尝试过的代码 【参考方案1】:

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 以使用支持缓存的异步图像下载器。

【讨论】:

【参考方案2】:
    NSString *path = [NSString stringWithFormat:@"%@/%@", baseUrl, imageName];
    NSURL *url = [NSURL URLWithString:path];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *imgage = [[UIImage alloc] initWithData:data];

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

【讨论】:

但是怎么会有单独的图片名数组!! 我会试着告诉你 NSString *path = [NSString stringWithFormat:@"%@/%@", baseUrl, [[yourImageArray valueForKey:@"category_image"] objectAtIndex: indexPath.row]]; 2017-06-13 10:36:09.619 MenuBar[1764:104943] URL: test.kre8tives.com/barebon/upload//(null) 状态码: 404, headers "Content-Encoding" =压缩包; “内容长度”= 256; “内容类型”=“文本/html;字符集=iso-8859-1”;日期 =“2017 年 6 月 13 日星期二 05:06:08 GMT”;服务器 = "Apache Phusion_Passenger/4.0.10 mod_bwlimited/1.4 mod_fcgid/2.3.9"; Vary = "接受编码"; 这是我的回应

以上是关于使用 url iOS 目标 c 附加数组的主要内容,如果未能解决你的问题,请参考以下文章

始终通过将当前时间与目标 c ios 中的数组匹配来触发通知

IOS - 目标 C,如何读取核心数据并将其存储到可变数组中

从 URL 获取图像并将其附加到数组

如何在iOS(目标c)中发送带有字典和数组的JSON?

如何将NSMutable数组附加到现有文件中

使用 Swift 将结构附加到数组(在 iOS 中失败,但在 Playgrounds 中失败)