【问题标题】:How to show Image with space in its name in objective c如何在目标c中显示名称中带有空格的图像
【发布时间】:2012-09-12 06:43:10
【问题描述】:

我想从 Url 在 imageview 中显示图像,并且它的名称中有空格...

// NSString* imageURL = @"http://dev.squealrs.com/imaging.php/image-name.jpg?height=45&noimg=100&image=/wp-content/uploads/sqbrands/GMT-July-cover1344489425.jpg";

NSString* imageURL = @"http://dev.squealrs.com/imaging.php/image-name.jpg?height=45&noimg=100&image=/wp-content/uploads/sqbrands/Sookie Stackhouse small1343970416.jpg";

NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageURL]];

UIImage* image = [[UIImage alloc] initWithData:imageData];
[ImageWithspace setImage:image];

但没有显示图像,因为未注释的 imageURL 在 imagename 中包含空格,如果我使用带注释的 imageURL 而不是在 imageview 中显示图像:( ....给我一些解决方案

【问题讨论】:

    标签: iphone objective-c ipad


    【解决方案1】:

    您需要对网址进行编码:

    NSString *encoded = [imageURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    

    【讨论】:

    • 使用 NSUTF8StringEncoding。编码确定百分比转义将描述哪些字节。如果您使用 ASCII,则不能保证重音字符可以保留,或者,如果可以,则不能保证以任何特定编码进行编码,因为这些字符不是 ASCII。此外,如果任何字符不是 Cocoa 使用的任何编码(例如几乎任何亚洲语言中的任何字符),该方法仍将返回 nil -Peter Hosey
    【解决方案2】:

    您需要先对 URL 进行编码,然后才能使用它来创建 NsURL。有一个内置类可以帮助您对字符串进行编码。

    下面是一个编码字符串以用于 NSURL 的示例:NSURL Encoding in ObjC

    【讨论】:

      【解决方案3】:
       NSURL *url = [[NSURL alloc] initWithString:[myurlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
      

      发生这种情况是因为 url 中的空格未被处理,因此使用了百分比编码

      【讨论】:

        【解决方案4】:
         NSString* imageURL = @"http://dev.squealrs.com/imaging.php/image-name.jpg?height=45&noimg=100&image=/wp-content/uploads/sqbrands/Sookie Stackhouse small1343970416.jpg";
        NSString *spaceUrl = [[NSString stringWithFormat:imageURL] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        spaceUrl = [spaceUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
        
        
        NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:spaceUrl]];
        
        UIImage* image = [[UIImage alloc] initWithData:imageData]
            [ImageWithspace setImage:image];
        

        只需复制粘贴此代码即可查看。如果您还有问题,请随时询问

        【讨论】:

          猜你喜欢
          • 2013-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-31
          • 2019-04-02
          • 1970-01-01
          • 2012-08-15
          • 1970-01-01
          相关资源
          最近更新 更多