iphone - NSURL URLWithString :myString returns Nil?

标签 iphone objective-c nsurl

我有一串我的 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/

相关文章:

iphone - 检索 iOS 设备标识符

ios - 为什么使用 viewWithTag 高效?

iphone - 使用页面控制?

ios - fatal error : Unexpectedly found nil while unwrapping an Optional value NSURL

iphone - 应用程序外订阅中还提供了通过促销代码解锁功能

ios - 如何在ios中制作不包含卸载选项的企业应用程序

iphone - iPhone上有音频压缩库吗?

ios - 暂停和恢复 Grand Central Dispatch 线程

swift - 迁移到 Swift 3 - 在 URL session 期间出现以下错误

ios - Swift - pathForResource inDirectory 参数