我想从 JSON URL 获取图像,但是在 IOS 中获取图像时出现了一些错误

Posted

技术标签:

【中文标题】我想从 JSON URL 获取图像,但是在 IOS 中获取图像时出现了一些错误【英文标题】:I want to get image from JSON URL, but I got some error to get the Image In IOS 【发布时间】:2016-05-05 09:52:29 【问题描述】:

我想从 JSON URL 获取图像,所以我需要在图像列表中使用 JSON 数组和 JSON 对象以显示在图像视图中,但是从 JSON 获取 JSON 数组时出现了一些错误。

JSON:


    "status": "200",
    "requestType": "bannerImages",
    "basePath": "http:\/\/192.168.0.33\/cartwebsite3\/",
    "bannerPath": "http:\/\/192.168.0.33\/cartwebsite3\/cdn-images\/banner\/",
    "response": 
        "data": [
            
                "banner_id": "37",
                "banner_name": "1457324300894ac3df08bd3648452703d8412f82c2.jpg",
                "banner_link": "",
                "banner_blocked": "0",
                "banner_created": "admin",
                "created_on": "1457324300"
            ,
            
                "banner_id": "36",
                "banner_name": "14573242986be953c24858a3c2d787d57e6b77be1f.jpg",
                "banner_link": "",
                "banner_blocked": "0",
                "banner_created": "admin",
                "created_on": "1457324298"
            ,
            
                "banner_id": "35",
                "banner_name": "1457324295f8d8153fb4f29d3af15276db22435d48.jpg",
                "banner_link": "",
                "banner_blocked": "0",
                "banner_created": "admin",
                "created_on": "1457324295"
            
        ]
    ,
    "request": 
        "postData": [],
        "getData": 
            "type": "bannerImages",
            "result": "json"
        
    

代码:

#import "ViewController.h"
#import "TableViewCell.h"

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kLatestKivaLoansURL [NSURL URLWithString:@"http://192.168.0.33/cartwebsite3/qcrest1.0/?type=bannerImages&result=json"]


@interface ViewController ()

    NSMutableArray *bannerPath_NameArr,*finalout;
    NSString *jsonString;
    NSArray *array;
    NSString *arr1;

@end

@implementation ViewController

- (void)viewDidLoad 
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
     statusarray=[[NSMutableArray alloc]init];

    dispatch_async(kBgQueue, ^ NSData *data=[NSData dataWithContentsOfURL:kLatestKivaLoansURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    );


   
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

    return self.contentview;


-(void)fetchedData:(NSData *)responseData


    NSError *error;

    NSDictionary *json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSMutableArray * outstatus = [json objectForKey:@"status"];
    NSLog(@"status %@", outstatus);
     jsonString = [jsonString stringByReplacingOccurrencesOfString:@"(\n" withString:@""];

    array = [[json objectForKey:@"response"]valueForKey:@"data"];

    NSString *arr3=[json objectForKey:@"bannerPath"];
    NSLog(@"%@",arr3);

    NSString *arr2=[json objectForKey:@"basePath"];
    NSLog(@"%@",arr2);

    [statusarray addObject:outstatus];
    [ban_path_arr addObject:arr3];
    [ban_base_arr addObject:arr2];

   NSDictionary *jsondic=[json valueForKeyPath:@"response.data"];
//    array = [[json objectForKey:@"response"] valueForKey:@"data"];
  NSArray *banname=[jsondic valueForKey:@"banner_name"];

    NSString *arr1=[json objectForKey:@"bannerPath"];
    array = [[json objectForKey:@"response"] valueForKey:@"data"];

//    for (int i=0; i<[banname count]; i++) 
//        NSArray *test=[banname objectAtIndex:i];
//        NSLog(@"%@",test);
//      imageURL = [NSString stringWithFormat:@"%@%@",arr3,test];
//     NSLog(@"URL= %@",imageURL);
//    
//    
    finalout=[[NSMutableArray alloc]init];
    [finalout addObject:imageURL];
    NSLog(@"array output %@",finalout);



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    return [finalout count];


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    static NSString *MyIdentifier = @"TableViewCell";

    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier forIndexPath:indexPath];
    if (cell == nil)

    
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];

        cell = [nib objectAtIndex:0];
    
    NSString *UrlFormat = [NSString stringWithFormat:@"%@%@",arr1,[[array objectAtIndex:indexPath.row] valueForKey:@"banner_name"]];
    NSLog(@"%@",UrlFormat);
    NSData *imageurl=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[finalout objectAtIndex:indexPath.row]]];

    cell.imgName.image=[UIImage imageWithData:imageurl];

    return cell;



- (void)didReceiveMemoryWarning

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

@end

日志错误:

2016-05-05 17:40:21.578 pageview[2302:151094] status 200
2016-05-05 17:40:21.579 pageview[2302:151094] http://192.168.0.33/cartwebsite3/cdn-images/banner/
2016-05-05 17:40:21.579 pageview[2302:151094] http://192.168.0.33/cartwebsite3/
2016-05-05 17:40:21.597 pageview[2302:151094] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010d9b1e65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010d42adeb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010d8788c5 -[__NSArrayM insertObject:atIndex:] + 901
    3   pageview                            0x000000010cf168e0 -[ViewController fetchedData:] + 976
    4   Foundation                          0x000000010d013067 __NSThreadPerformPerform + 283
    5   CoreFoundation                      0x000000010d8dda31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    6   CoreFoundation                      0x000000010d8d395c __CFRunLoopDoSources0 + 556
    7   CoreFoundation                      0x000000010d8d2e13 __CFRunLoopRun + 867
    8   CoreFoundation                      0x000000010d8d2828 CFRunLoopRunSpecific + 488
    9   GraphicsServices                    0x00000001120b5ad2 GSEventRunModal + 161
    10  UIKit                               0x000000010df86610 UIApplicationMain + 171
    11  pageview                            0x000000010cf1afdf main + 111
    12  libdyld.dylib                       0x000000011031592d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

for 循环出错,我不知道如何使用 for 循环转换 JSON 数组以获取 Image View 中的所有图像。

我该如何解决这个问题。很高兴知道。

【问题讨论】:

将此行 NSArray* nsJson= [[NSString alloc] initWithData:jsondic encoding:NSUTF8StringEncoding]; 更改为 NSArray* nsJson= [[json valueForKeyPath:@"response"] valueForKey:@"data"] 【参考方案1】:

试试这个代码,它将帮助你获取图像

NSString *myImage = [imageArray objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString: images];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
cell. imgview.image = [UIImage imageNamed:img];

【讨论】:

你的代码和提问者代码有什么区别 这段代码没有问题,序列化有问题,检查一次并修改你的答案 @Anbu.Karthik 我正在使用相同的代码从 json 数据中获取图像 您的代码很好,但问题不在此处,正在接收的数据字节丢失【参考方案2】:

请检查您的“finalout”数组是否包含正确的索引数据。数组未以正确格式获取数据。您应该使用 for 循环并将图像网址一一存储在“finalout”数组中。

【讨论】:

请试试这个 NSMutableArray * jsonarray = [[NSMutableArray alloc] init]; jsonarray = [oDict objectForKey:@"prod_info"]; for(int i=0;i【参考方案3】:

使用此代码,

声明变量:

@interface ListViewController () 
    NSString *arr1;


@end

获取方法:

-(void)fetchedData:(NSData *)responseData


    NSError *error;

    NSDictionary *json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSMutableArray * outstatus = [json objectForKey:@"status"];
    NSLog(@"status %@", outstatus);

    arr1=[json objectForKey:@"bannerPath"];
    finalout = [[json objectForKey:@"response"]valueForKey:@"data"];
    NSLog(@"print %@", finalout);
    // if you get the value its working fine.

    [tableviewname reloadData];


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    return [finalout count];

如果所有数据值都存储在数组中,那么

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    static NSString *MyIdentifier = @"TableViewCell";

    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier forIndexPath:indexPath];
    if (cell == nil)

    
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];

        cell = [nib objectAtIndex:0];
    

   NSString UrlFormat = [NSString stringWithFormat:@"%@%@",arr1,[[array objectAtIndex:indexPath.row] valueForKey:@"banner_name"]];

    NSData *imageurl=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:UrlFormat]];

    cell.imgName.image=[UIImage imageWithData:imageurl];

    return cell;


在您的源代码中更改上述代码,请更改方法fetchedData希望对您有帮助

【讨论】:

我使用了你的代码,但是我得到了错误 object cannot be nill 是的,我收到了错误,对象内部的 JSON 显示错误。 它在哪里,你有什么链接吗? 不,我修改了上面问的问题,你可以检查一下 你的错误是finalout=[[NSMutableArray alloc]init]; [finalout addObject:imageURL]; NSLog(@"array output %@",finalout);隐藏这些行,然后在所有委托中将数组值 finalout 更改为 array 变量

以上是关于我想从 JSON URL 获取图像,但是在 IOS 中获取图像时出现了一些错误的主要内容,如果未能解决你的问题,请参考以下文章

从 ios 中的 Url 获取多个图像

来自 json 文件的图像未显示在网站上

从 Javascript 中的 url 获取 JSON 文件,React Native

我想从这个 JSON URL 回显 IMDB ID、标题、质量和嵌入 URL

如何在 swift 4 中从图像选择器获取照片本地 url

Ruby on Rails |我想从 ActiveStorage 中获取 Best Seller Taxonomy 的图像 标题已获取并显示在屏幕上,但图像不是