使用哈希标记搜索打开本机Twitter应用

时间:2012-06-11 14:11:00

标签: objective-c ios twitter nsurl hashtag

在iOS 5上,我正在尝试使用动态主题标签搜索术语打开本机Twitter应用。

我试过了:

- (void)openForHashTag:(NSString *)hashTag {
UIApplication *app = [UIApplication sharedApplication];

NSURL *twitterURL = [NSURL URLWithString:[NSString stringWithFormat:@"twitter://search?q=%@", hashTag]];
DLog(@"Hashtag URL: %@ ", twitterURL);

if ([app canOpenURL:twitterURL]) {
    [app openURL:twitterURL];
}
else {
    NSURL *safariURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://mobile.twitter.com/search?q=%@", hashTag]];
    [app openURL:safariURL];
}

}

它似乎转到了主题标签搜索页面,但是会花费永远加载... twitter://search?q=%@格式是否错误?

4 个答案:

答案 0 :(得分:3)

- (void)openForHashTag:(NSString *)hashTag {
    UIApplication *app = [UIApplication sharedApplication];

    // NOTE: you must percent escape the query (# becomes %23)
    NSString *cleanQuery = [hashTag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *twitterURL = [NSURL URLWithString:[NSString stringWithFormat:@"twitter://search?query=%@", cleanQuery]];
    if ([app canOpenURL:twitterURL]) {
        [app openURL:twitterURL];
    } else {
        NSURL *safariURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://mobile.twitter.com/search?q=%@", cleanQuery]];
        [app openURL:safariURL];
    }
}

答案 1 :(得分:2)

打开Twitter应用并搜索主题标签的正确网址是

twitter://search?query=hashtag

答案 2 :(得分:1)

好吧,经过大量的讨论,我意识到散列标记的搜索查询不应包含实际的散列标记...因此通过添加行

 NSString *cleanString = [hashTag stringByReplacingOccurrencesOfString:@"#" withString:@""];

它现在工作正常......神秘解决了。

答案 3 :(得分:0)

Swift 3.0 +

更新上述代码的快速版本

       private func openTwitterHashTag() {

           // self.viewModel.programInfo.twitterHash = "#tag"

            guard let hashTagQuery = self.viewModel.programInfo.twitterHash.addingPercentEncoding(
                withAllowedCharacters: .urlHostAllowed
            ) else { return }

            // CASE: OPEN IN NATIVE TWITTER APP
            if let twitterUrl = URL(string: "twitter://search?query=\(hashTagQuery)"),
                UIApplication.shared.canOpenURL(twitterUrl) {
                UIApplication.shared.open(twitterUrl, options: [:], completionHandler: nil)
                return
            }

            // CASE: OPEN ON SAFARI VIEW CONTROLLER
            if let twitterWebUrl = URL(string: "http://mobile.twitter.com/search?q=\(hashTagQuery)") {
                let svc = SFSafariViewController.init(url: twitterWebUrl)
                self.present(svc, animated: true, completion: nil)
            }
        }

还可以在 info.plist

中添加权限
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
</array>