简体   繁体   中英

Open Twitter from iOS App Not Working Correctly

I have been using the following code to open Twitter inside my app. While it works, I can't seem to embed spaces in the NSString.

NSString *string1 = [NSString stringWithFormat:@"twitter://post?message=hello+world"];
NSString *string2 = [NSString stringWithFormat:@"http://twitter.com/intent/tweet?text=hello%20world"];

NSURL *twitterURL = [NSURL URLWithString:string1];
NSURL *mobileURL = [NSURL URLWithString:string2];

if ([[UIApplication sharedApplication] canOpenURL:twitterURL])
    [[UIApplication sharedApplication] openURL:twitterURL];
else
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mobileURL]];

Both parts of the code work in the intended situations, but how can I embed spaces in the NSURL? The second piece of code prints "hello2orld" instead of "hello world". I also tried the + delimiter to no avail.

You can convert spaces to %20 with this instruction:

NSString *string1 = [NSString stringWithFormat:@"twitter://post?message=hello world"];
string1 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Also you can remove this encoding using other NSString method:

– stringByReplacingPercentEscapesUsingEncoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM