简体   繁体   中英

Objective-C: Get Image from JSON

I am trying to learn web service on iOS.

I'm starting of from getting an image from a JSON api link.

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'

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.

    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.

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). You can set app accept like this: 在此处输入图片说明

You are adding popUpBanner in view after getting image from server. so you have to initialize it before in viewdidload and need to set it's frame.

Then set image to popUpBanner from completion handler of web service on main thread. 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.

 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.

And make sure that you are getting image object using breakpoint.

Hope this will help :)

@@@require suppurate api to load image. 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.@@@

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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