繁体   English   中英

Objective-C:从JSON获取图像

[英]Objective-C: Get Image from JSON

我正在尝试学习iOS上的Web服务。

我从从JSON API链接获取图像开始。

我使用了下面的代码,但是图像没有显示,并且我收到警告说

不兼容的指针类型从'NSSting * _Nullable'分配给'UIImage * _Nullable'

我的密码

NSURL *urlAdPop = [NSURL URLWithString:@"JSON LINK HERE"];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                       error:NULL];
             popUpBanner.image = [[AdPopUp objectForKey:@"ad_image"] stringValue];
             popUpAdURL = [AdPopUp objectForKey:@"ad_link"];
         }
     }];



    popUpBanner.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:popUpAdURL]];
    popUpBanner.hidden = NO;
    popUpBanner.layer.cornerRadius = 9;
    popUpBanner.clipsToBounds = YES;
    popUpBanner.userInteractionEnabled = YES;
    [self.view addSubview:popUpBanner];
popUpBanner.layer.cornerRadius = 9;
popUpBanner.clipsToBounds = YES;
popUpBanner.userInteractionEnabled = YES;
popUpBanner.hidden = YES;
[self.view addSubview:popUpBanner];

NSString* strURL=@"JSON LINK HERE";
NSString* webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *urlAdPop = [NSURL URLWithString:webStringURL];
NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response,
                                           NSData *data, NSError *connectionError)
 {
     if (data.length > 0 && connectionError == nil)
     {
         NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                   error:NULL];


         popUpAdURL = [AdPopUp objectForKey:@"ad_link"];
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{      
         NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[AdPopUp objectForKey:@"ad_image"]]]];
        if (imgData)
          {

            UIImage *image = [UIImage imageWithData:imgData];
            if (image)
              {
            dispatch_async(dispatch_get_main_queue(), ^{
                 popUpBanner.image = image;
                 popUpBanner.hidden = NO;

            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{

            });
        }
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{

        });
    }
    });

     }
 }];

完美的图像显示方式!

希望它会帮助你:)

从Web服务获得响应后,需要在块内编写代码。

    NSURL *urlAdPop = [NSURL URLWithString:@"JSON LINK HERE"];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlAdPop];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary *AdPopUp = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:0
                                                                       error:NULL];
             popUpBanner.image = [[AdPopUp objectForKey:@"ad_image"] stringValue];
             popUpAdURL = [AdPopUp objectForKey:@"ad_link"];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:popUpAdURL]];

             dispatch_async(dispatch_get_main_queue(), ^{ // get main thread to update image
                  popUpBanner.image= image
                  popUpBanner.hidden = NO;
                 popUpBanner.layer.cornerRadius = 9;
                 popUpBanner.clipsToBounds = YES;
                 popUpBanner.userInteractionEnabled = YES;
                 [self.view addSubview:popUpBanner];

             });
         }
     }];

如果您需要处理来自Web响应的图像,则可以使用GitHub上的SDWebImage库。

在其自述页面中,他们还提供了实现方法。

#import <SDWebImage/UIImageView+WebCache.h>

[self.YourImageView sd_setImageWithURL:[NSURL URLWithString:@"http://yourimagePath/.../"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

而已 !

首先,检查该网址在浏览器中是否可用。 如果是,请检查您的应用是否接受HTTP(非HTTPS)。 您可以这样设置应用程序接受: 在此处输入图片说明

从服务器获取图像后,正在view中添加popUpBanner 因此,您必须先在viewdidload中对其进行初始化,并需要设置其框架。

然后将图像从主线程上的Web服务的完成处理程序设置为popUpBanner 并确保您必须设置图像而不是图像名称字符串!

下一行是错误的,它正在尝试将字符串设置为imageview,这是不可能的。

 popUpBanner.image = [[AdPopUp objectForKey:@"ad_image"] stringValue];

从服务端提供的image url获取图像,并使用响应得到的图像名称。

并确保使用断点获取图像对象。

希望这会有所帮助:)

@@@需要suppurate api来加载图像。 希望将链接和图像名称附加在一起才能到达。 因此,需要两个字符串来存储api和图像名称。@@@

s=[[mutarray objectAtIndex:index]valueForKey:@"image"];

        NSString *f=[NSString stringWithFormat:@"http://iroidtech.com/wecare/uploads/news_events/%@",s];

        NSURL *g=[[NSURL alloc]initWithString:f];
        data=[NSMutableData dataWithContentsOfURL:g];
        self.imgvw.image=[UIImage imageWithData:data];
        _descrilbl.text=[[mutarray objectAtIndex:index]valueForKey:@"image"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM