NSURL 和 NSURLConnection 不适用于 Google Chart API

发布于 2024-11-02 19:28:51 字数 741 浏览 0 评论 0原文

我尝试显示 Google Chart API 返回的图像,但以下代码不起作用:

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;

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"]] returningResponse:nil error:nil];
UIImage *downloadedImage = [UIImage imageWithData:imageData];
imgView.image = downloadedImage;

目标图像未按预期显示。您知道问题出在哪里吗?

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"]] returningResponse: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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2024-11-09 19:28:52

这两段代码都有效,除了 NSURL 对象为零。 NSURL 不支持管道字符 (|),因此需要使用 %7c 进行转义。您可以使用 [NSString stringByAddingPercentEscapesUsingEncoding:] 来处理任何其他字符。这是新版本:

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;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文