I tried to display an image returned by Google Chart API, but the codes below do not work:
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World"]];
UIImage *downloadedImage = [UIImage imageWithData:imageData];
imgView.image = downloadedImage;
or
NSData *imageData=[NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World"]] returni开发者_JAVA百科ngResponse:nil error:nil];
UIImage *downloadedImage = [UIImage imageWithData:imageData];
imgView.image = downloadedImage;
The target image was not shown as expected. Do you have any idea where the problem was?
Both pieces of code work, except the NSURL object is nil. NSURL does not support pipe characters (|), so you need to escape it with %7c. You could use [NSString stringByAddingPercentEscapesUsingEncoding:] to take care of any other characters. Here is the new version:
NSString *url = [@"http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *downloadedImage = [UIImage imageWithData:imageData];
imgView.image = downloadedImage;
加载中,请稍侯......
精彩评论