问题描述
我有一个URL字符串.我想从该URL获取数据.为此,我需要创建NSURL
的对象.问题是,当我尝试NSURL类的URLWithString
方法时,它返回nil.但是,当我在Mac的Safari中打开此链接时,它将向我显示图像.
I have a string of my url.. I want to get data from that url. For that I needs to create object of NSURL
. The problem is while I try URLWithString
method of NSURL class it returns nil. But when I opens this link in Safari of My Mac it display me the Image.
我正在使用..
NSString *str = @"http://chart.apis.google.com/chart?chs=150x150&cht=qr&chld=L|0&chl=http://MyServer.com/shareMyCard.php?value=1304057103";
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
我不知道为什么URL为Nil.我认为是因为我的字符串中有查询字符串.
I don't know why the URL is Nil. I think because of query string in my string.
任何想法如何从此网址字符串获取数据.
Any Idea how to get data from this Url String.
谢谢
推荐答案
您的URL为零,因为它包含特殊字符,请使用以下函数对您的url参数进行编码,然后再在URL中使用它们-
Your URL is nil because it contains special chars, use this following function to encode your url parameters before using them in URL -
-(NSString *) URLEncodeString:(NSString *) str
{
NSMutableString *tempStr = [NSMutableString stringWithString:str];
[tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
return [[NSString stringWithFormat:@"%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
这篇关于NSURL URLWithString:myString返回Nil吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!