3

在 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

4 回答 4

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];
    }
}
于 2012-12-12T17:44:17.543 回答
2

打开 Twitter 应用程序和搜索主题标签的正确 URL 是

twitter://search?query=hashtag
于 2012-09-28T12:18:26.553 回答
1

好吧,经过一番摸索,我意识到哈希标签的搜索查询不应该包含实际的哈希标签......因此通过添加行

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

它现在工作正常......谜团解决了。

于 2012-06-11T15:05:47.240 回答
1

斯威夫特 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>
于 2018-06-27T12:59:23.403 回答