2011-04-20 44 views
1

我試圖顯示由谷歌圖表API返回的形象,但下面的代碼將不會工作:NSURL和NSURLConnection的不與谷歌圖表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; 

目標圖像未按預期顯示。你知道問題出在哪裏嗎?

回答

-1

這兩個代碼段的工作,除了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;