我有一串我的 url.. 我想从那个 url 获取数据。为此,我需要创建 NSURL
的对象。问题是当我尝试 NSURL 类的 URLWithString
方法时它返回 nil。但是,当我在我的 Mac 的 Safari 中打开此链接时,它会显示图像。
我正在使用..
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。我想是因为我的字符串中有查询字符串。
知道如何从此 Url 字符串获取数据。
谢谢
最佳答案
您的 URL 为 nil 因为它包含特殊字符,请使用以下函数对您的 url 参数进行编码,然后再在 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];
}
关于iphone - NSURL URLWithString :myString returns Nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839877/