簡體   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