如何在我的iPhone应用程序中从Twitter应用程序打开Twitter页面?

23

我想要使用Twitter应用程序打开的页面:

https://twitter.com/#!/PAGE

我使用以下代码来打开Twitter应用程序:

NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:@"%@", @"twitter://https://twitter.com/#!/PAGE"]];
[[UIApplication sharedApplication] openURL:urlApp];
但是这段代码似乎没有按预期工作,我只启动了 Twitter 应用程序而没有显示我想要的页面。
5个回答

41
你正在寻找以下网址:
twitter:///user?screen_name=PAGE

请注意,Twitter并非所有设备都安装了。您应该检查openURL方法的结果。如果失败,请使用常规url在Safari中打开页面。


9
此答案的URL中显示了三个正斜杠。使用两个正斜杠对我有效。 - software evolved
https://twitter.com/intent?text=hello 这样的意图,它的 URL 会是什么样子? - Kevin Hernandez

14

我知道这个问题的回复有些晚了,我同意Murat的回答是完全正确的。 只需添加以下检查:

NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:@"%@", @"twitter:///user?screen_name=PAGE]];

if ([[UIApplication sharedApplication] canOpenURL:urlApp]){
        [[UIApplication sharedApplication] openURL:urlApp];
    }

希望这能对某人有所帮助。干杯!!:)


14
以下代码会在已安装 Twitter 应用的情况下打开 Twitter 页面,否则将在 Safari 中打开 Twitter:
```

以下代码会在已安装 Twitter 应用的情况下打开 Twitter 页面,否则将在 Safari 中打开 Twitter:

```
NSURL *twitterURL = [NSURL URLWithString:@"twitter://user?screen_name=username"];
if ([[UIApplication sharedApplication] canOpenURL:twitterURL])
    [[UIApplication sharedApplication] openURL:twitterURL];
else
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.twitter.com/username"]];

不要忘记将“username”替换为你的名字。


2
还要记得在info.plist中添加LSApplicationQueriesSchemes。 - appthumb

6

这是在Swift中所需的完整代码。我正在使用Swift 4,但我认为Swift 3也是一样的。

let Username =  "YOUR_USERNAME_HERE" 
let appURL = NSURL(string: "twitter:///user?screen_name=\(Username)")!
let webURL = NSURL(string: "https://twitter.com/\(Username)")!
let application = UIApplication.shared
if application.canOpenURL(appURL as URL) {
      application.open(appURL as URL)
    } else {
        // if Twitter app is not installed, open URL inside Safari
        application.open(webURL as URL)
    }

不要忘记添加使用canOpenURL所需的信息键: 所需信息键


2
你能告诉我你是如何找到的吗?有官方文档吗? - Khushneet

2

@Alexey: 如果你只是想知道如何从你的应用程序中启动Twitter,请按照以下步骤操作:

NSURL *urlApp = [NSURL URLWithString: [NSString stringWithFormat:@"%@", @"twitter://"]];
   if ([[UIApplication sharedApplication] canOpenURL:urlApp]){
        [[UIApplication sharedApplication] openURL:urlApp];
   }else{
        UIAlertView *appMissingAlertView = [[UIAlertView alloc] initWithTitle:@"Twitter App Not Installed!" message:@"Please install the Twitter App on your iPhone." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
        [appMissingAlertView show];
        [appMissingAlertView release];
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接