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

时间:2016-05-05 09:52:29

标签: ios objective-c json xcode parsing

我想从JSON URL获取图像,所以我需要在图像列表中使用JSON数组和JSON对象才能在Image View中显示,但是我从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"
        }
    }
}

CODE:

#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数组以获取图像视图中的所有图像。

我该如何解决这个问题。很高兴能够帮助他们。

3 个答案:

答案 0 :(得分:0)

尝试此代码,它将帮助您获取图像

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

答案 1 :(得分:0)

使用此代码,

声明变量:

@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 希望其有用

答案 2 :(得分:0)

请检查您的&#34; finalout&#34;数组不包含索引方面的正确数据。数组不能以正确的格式获取数据。你应该使用for循环并逐个存储&#34; finalout&#34;阵列。