Reputation: 8236
On iOS 5, I'm trying to open a native twitter app with a dynamic hashtag search term.
I've tried:
- (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];
}
}
It seems to go to the hashtag search page, but spends forever loading... Is twitter://search?q=%@
the wrong format?
Upvotes: 3
Views: 1522
Reputation: 3718
Updating swift version of above code
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)
}
}
Also Add permission in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twitter</string>
</array>
Upvotes: 1
Reputation: 16916
- (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];
}
}
Upvotes: 3
Reputation: 371
The proper URL for opening the Twitter app and searching for a hashtag is
twitter://search?query=hashtag
Upvotes: 2
Reputation: 8236
Well, after a lot of head scratching, I realised that the search query for a hash tag should not contain an actual hash tag... Therefore by adding the line
NSString *cleanString = [hashTag stringByReplacingOccurrencesOfString:@"#" withString:@""];
it now works fine... Mystery solved.
Upvotes: 1