简体   繁体   English

Objective-C:从JSON获取图像

[英]Objective-C: Get Image from JSON

I am trying to learn web service on iOS. 我正在尝试学习iOS上的Web服务。

I'm starting of from getting an image from a JSON api link. 我从从JSON API链接获取图像开始。

I've used the code below but the image is not displaying and I'm getting warning that says 我使用了下面的代码,但是图像没有显示,并且我收到警告说

Incompatible pointer types assigning to 'UIImage * _Nullable' from 'NSSting * _Nullable' 不兼容的指针类型从'NSSting * _Nullable'分配给'UIImage * _Nullable'

My code 我的密码

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(), ^{

        });
    }
    });

     }
 }];

Perfect way to display image! 完美的图像显示方式!

Hope It will help you :) 希望它会帮助你:)

You need to write your code inside block after you get response from webservice. 从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];

             });
         }
     }];

If you need to deal with images comes from web response then you can use SDWebImage library from GitHub. 如果您需要处理来自Web响应的图像,则可以使用GitHub上的SDWebImage库。

In its read me page they have also provided the way how you can achieve it. 在其自述页面中,他们还提供了实现方法。

#import <SDWebImage/UIImageView+WebCache.h>

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

Thats it ! 而已 !

Firstly,check if that url available in browser. 首先,检查该网址在浏览器中是否可用。 If yes,check if your app accept HTTP(not HTTPS). 如果是,请检查您的应用是否接受HTTP(非HTTPS)。 You can set app accept like this: 您可以这样设置应用程序接受: 在此处输入图片说明

You are adding popUpBanner in view after getting image from server. 从服务器获取图像后,正在view中添加popUpBanner so you have to initialize it before in viewdidload and need to set it's frame. 因此,您必须先在viewdidload中对其进行初始化,并需要设置其框架。

Then set image to popUpBanner from completion handler of web service on main thread. 然后将图像从主线程上的Web服务的完成处理程序设置为popUpBanner And make sure that you have to set image not image name string! 并确保您必须设置图像而不是图像名称字符串!

Below line is wrong, it is trying to set string to imageview which is not possible. 下一行是错误的,它正在尝试将字符串设置为imageview,这是不可能的。

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

get image from image url provided by service side and use image name that you get in response. 从服务端提供的image url获取图像,并使用响应得到的图像名称。

And make sure that you are getting image object using breakpoint. 并确保使用断点获取图像对象。

Hope this will help :) 希望这会有所帮助:)

@@@require suppurate api to load image. @@@需要suppurate api来加载图像。 want to attach the link and image name together as to reach. 希望将链接和图像名称附加在一起才能到达。 thus two strings are needed to store each the api and the image name.@@@ 因此,需要两个字符串来存储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