我有一个视图控制器,其中包含UIImageView
和UILabel
。如何使用数组从JSON加载图像和数据?这是我的代码
-(void)viewDidLoad
{
[super viewDidLoad];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:"www.example.com"]];
connection4 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection4 start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (connection == connection4)
{
myDataQA = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connection == connection4)
{
[myDataQA appendData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == connection4)
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:myDataQA options:NSJSONReadingAllowFragments error:nil];
fldExamTitleArray = [dic valueForKey:@"fldexamtitle"];
fldExamStartArray = [dic valueForKey:@"examdate"];
ListBannerArray = [dic valueForKey:@"listBanner"];
}
}
在我的代码中,ListBannerArray
包含:
" listbanner":" HTTP:demo.example.com/1.png
答案 0 :(得分:0)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == connection4)
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:myDataQA options:NSJSONReadingAllowFragments error:nil];
fldExamTitleArray = [dic valueForKey:@"fldexamtitle"];
fldExamStartArray = [dic valueForKey:@"examdate"];
ListBannerArray = [dic valueForKey:@"listBanner"];
for(int i = 0 ; i < ListBannerArray.count;i++)
{
UIImage* myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString: [ListBannerArray objectAtIndex: i ]]];
yourimageview.image = myimage;
your_Label.text = [fldExamTitleArray objectAtIndex : i];
}
}
}
答案 1 :(得分:0)
首先,你必须循环你的数组和数组包含字典。所以你需要从该字典中获取图像网址。之后,您可以像这样加载图像。
NSString *ImageURL = @"YourURLHere";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
imageView.image = [UIImage imageWithData:imageData];