如何从URL获取图像并放入NSArray?

时间:2017-03-31 04:05:16

标签: ios objective-c arrays uiimage nsurl

我想从网址获取图片并将其放入NSArray中,但在下面的代码中不起作用,请帮助:

@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {

    NSString *imageUrlStringAA=@"http://aaa.net/AA.png";
    NSString *imageUrlStringBB=@"http://aaa.net/BB.png";

    NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
    NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];

    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];

任何想法都表示赞赏,谢谢。

2 个答案:

答案 0 :(得分:0)

首先从http协议下载任何内容然后在info.plist中添加以下词汇

Allow http protocol

现在试试这段代码:

@interface DataViewController ()

@property (readonly, strong, nonatomic) NSArray *picData;

@end

@implementation DataViewController

- (void)viewDidLoad {
   NSString *imageUrlStringAA=@"http://www.hdwallpapers.in/download/antelope_canyon-360x640.jpg";
   NSString *imageUrlStringBB=@"http://www.hdwallpapers.in/download/vegeta_dragon_ball_super-360x640.jpg";

   NSURL *urlAA=[NSURL URLWithString:imageUrlStringAA];
   NSURL *urlBB=[NSURL URLWithString:imageUrlStringBB];

    NSData *dataAA=[[NSData alloc] initWithContentsOfURL:urlAA];
    NSData *dataBB=[[NSData alloc] initWithContentsOfURL:urlBB];

    UIImage *imageAA=[UIImage imageWithData:dataAA];
    UIImage *imageBB=[UIImage imageWithData:dataBB];
    _picData = [NSArray arrayWithObjects:imageAA, imageBB, nil];
}

答案 1 :(得分:0)

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{

        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
                                                 [NSURL URLWithString:@"Image URL"]]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            if(image!= nil){
                [[cell myimage] setImage:image];

            }else{
                UIImage * image = [UIImage imageNamed:@"PLACEHOLDER"];
                [[cell myimage] setImage:image];

            }


            [cell setNeedsLayout];
        });
    });

试试这些......