将json数据图像解析为图像视图

时间:2014-01-31 06:17:20

标签: ios objective-c json

这是我的JSON回复,

 {
        "AppConfig": {
            "store_logo": "url",
            "deal_status": "A",
            "see_the_menu_btn": "A",
            "store_id": "3",
            "store_name": "  Pizza Restaurant",
            "bg_image": "www.my image.png"
        }
    }

 NSString *localwthr = [NSString stringWithFormat:@"my url"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:localwthr]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (responsedata) {
        NSDictionary *Dictionarydetails = [NSJSONSerialization
                                           JSONObjectWithData:responsedata
                                           options:kNilOptions
                                           error:nil];
        NSLog(@"The return data is: %@",Dictionarydetails);

        NSString *imgURL=[[Dictionarydetails objectForKey:@"AppConfig"]objectForKey:@"bg_image"];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
        imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
    }
}

我需要获取密钥bg_image的网址值,下载图片并在UIImageView中设置。我怎么能这样做?

4 个答案:

答案 0 :(得分:2)

imageUrl永远不会像“www.my image.png”, imageUrl就像“http://www.serverName.com/directory/..../imageName.png

如果您的网址中有空格,则必须将其转换为UTF8格式,这是webURL的标准格式。 所以你应该使用,

imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//Use it as it shown in below code.

NSString *imgURL=[[jsonDict objectForKey:@"AppConfig"]objectForKey:@"bg_image"];
    imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];

喝彩!

答案 1 :(得分:1)

从网址加载图片,然后

NSString *imgURL=[[jsonDict objectForKey:@"AppConfig"]objectForKey:@"bg_image"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];

答案 2 :(得分:0)

查看此代码,这是否是您需要的,因为rmaddy告诉您已完成的代码到目前为止

NSString *imageName=[[jsonDict objectForKey:@"AppConfig"]objectForKey:@"bg_image"];
imageview.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imageName]]];

答案 3 :(得分:0)

试试这个:

NSString *imgURL=[[jsonDict objectForKey:@"AppConfig"]objectForKey:@"bg_image"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];