无法在iPhone应用中加载带空格或主题标签的NSURL

Ale*_*lex 14 iphone space escaping nsurl

Twitter有一个很好的功能,允许您使用以下格式预加载状态消息:

http://twitter.com/?status=@HelloWorld Hello World
Run Code Online (Sandbox Code Playgroud)

或者:

http://twitter.com/?status=%40HelloWorld%20Hello%20World
Run Code Online (Sandbox Code Playgroud)

我正在尝试在我的iPhone应用程序中添加一个按钮,该按钮将打开Safari以上预先填充的推文.

但是我遇到了百分号被双重逃逸的问题.

这是我尝试过的代码:

首先是一个有用的例子

NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
        NSLog(@"%@%@",@"Failed to open url:",[url description]);
Run Code Online (Sandbox Code Playgroud)

此代码的作用类似于魅力和输出:

http://twitter.com/?status=%40HelloWorld
Run Code Online (Sandbox Code Playgroud)

代码不起作用

NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld Hello World";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
        NSLog(@"%@%@",@"Failed to open url:",[url description]);
Run Code Online (Sandbox Code Playgroud)

这会创建一个null NSURL.我只能假设因为URLWithString不接受带有空格的文本.

所以我尝试了这段代码:

NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld%20Hello%20World";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
   NSLog(@"%@%@",@"Failed to open url:",[url description]);
Run Code Online (Sandbox Code Playgroud)

但是,这会创建URL:

http://twitter.com/?status=%40HelloWorld%2520Hello%2520World
Run Code Online (Sandbox Code Playgroud)

所以我已经逃过了我的百分号%,这当然不是我想要的.

当然人们一直在谈论使用函数:stringByAddingPercentEscapesUsingEncoding

所以我写了这段代码:

NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld%20Hello%20World";
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
    NSLog(@"%@%@",@"Failed to open url:",[url description]);
Run Code Online (Sandbox Code Playgroud)

但是你再次遇到双重逃逸问题:

http://twitter.com/?status=%40HelloWorld%2520Hello%2520World
Run Code Online (Sandbox Code Playgroud)

我希望有人可能知道某种工作.理想情况下,我还想包括主题标签,但是现在只是获得空格将是一个巨大的进步.

Ale*_*lex 21

事实证明,问题不是由NSURL对象引起的,而是由Twitter本身引起的.

这是正确的代码:

NSString* urlText = @"http://twitter.com/home?status=@HelloWorld Hello World";
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
    NSLog(@"%@%@",@"Failed to open url:",[url description]);
Run Code Online (Sandbox Code Playgroud)

关于twitter,我没有意识到的一件事是使用这个推特地址:

http://www.twitter.com/home?status=
Run Code Online (Sandbox Code Playgroud)

将自动逃避您的状态.

而:

http://twitter.com/home?status=
Run Code Online (Sandbox Code Playgroud)

不会自动逃脱.