Swift:通过Twitter分享文本

4

基本上我正在制作一个事件应用程序。一切都进行得很顺利,但是只有在Twitter上分享活动会出现问题。

我已经搜索了互联网,但我找到的都是使用Twitter的原生应用程序,而我不想这样做。我想使用浏览器来发推文。

我已经实现了Facebook分享的方法。

任何想法都将对我有很大帮助。

let content = FBSDKShareLinkContent()

    content.contentURL=NSURL(string: "http://facebook.com")
    content.imageURL = NSURL(string: "http://facebook.com")

    content.contentTitle = "Shou 3emlin test app "
    content.contentDescription = "testing testing testing"

    let shareDialog = FBSDKShareDialog()
    shareDialog.fromViewController = self
    shareDialog.mode=FBSDKShareDialogMode.Browser
    shareDialog.shareContent = content


    if !shareDialog.canShow() {
        shareDialog.mode=FBSDKShareDialogMode.Native
        shareDialog.shareContent = content
    }

    if shareDialog.canShow() {
        shareDialog.show()
    }
5个回答

27

将以下代码放入一个按钮的事件方法中,或者放在您想要使用浏览器发推文的方法中(Swift 3.0)

let tweetText = "your text"
let tweetUrl = "http://stackoverflow.com/"

let shareString = "https://twitter.com/intent/tweet?text=\(tweetText)&url=\(tweetUrl)"

// encode a space to %20 for example
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

// cast to an url
let url = URL(string: escapedShareString)

// open in safari
UIApplication.shared.openURL(url!)

结果:

这里输入图片描述


1
发现如果用户已经安装了 Twitter 应用程序,则会打开它而不是 Safari,这甚至更好,因为它看起来更本地化。谢谢。 - Vitalii
没有Twitter应用程序打开@Vitalii - Jigar Fumakiya

5

@ronatory的解决方案非常好用。如果用户设备上已经安装了Twitter应用程序,它还可以打开Twitter应用程序。

对于Swift 5+,请使用UIApplication.shared.open(url!)代替UIApplication.shared.openURL(url!),因为它已经被弃用了。


4
请看 Fabric.io。这个软件开发工具包允许你从你的应用程序中直接发布推文。
let composer = TWTRComposer()

composer.setText("just setting up my Fabric")
composer.setImage(UIImage(named: "fabric"))

// Called from a UIViewController
composer.showFromViewController(self) { result in
    if (result == TWTRComposerResult.Cancelled) {
         print("Tweet composition cancelled")
    }
    else {
       print("Sending tweet!")
    }
}

2
从今天起,Twitter Kit 很快就会被停用。最好不要选择它,而是看看其他选项。 - Vitalii

4
let tweetText = "hy" 
let tweetUrl = "http://rimmi/" 

let shareString = "https://twitter.com/intent/tweet?text=\(tweetText)&url=\(tweetUrl)"

// encode a space to %20 for example 
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

// cast to an url 
let url = URL(string: escapedShareString)

// open in safari 
UIApplication.shared.openURL(url!)

0

在SwiftUI Swift5中使用

Button {
    let tweetText = "Text for share"
    let shareString = "https://twitter.com/intent/tweet?text=\(tweetText)"
    let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
    let url = URL(string: escapedShareString)
    UIApplication.shared.open(url!)
} label: {
    Text("Share on Twitter")
}

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