LoginSignup
3
2

More than 3 years have passed since last update.

[cocoa][swift][Kotlin]Tweeting

Last updated at Posted at 2019-08-27

システム側でのSNS共有のサポートが終了したり、公式のTwitter Kit SDKのサポートが停止するなどで、スマートフォン・アプリケーションにTweet機能を組み込む方法が変わってきているので、今時点のTweet機能を組み込む方法を調べてみた。

  • ios
    • Social.framework
      iOS11から廃止。
    • Twitter Kit SDK
      2018年10月末でサポート終了。
  • Android
    • Twitter Kit SDK
      2018年10月末でサポート終了。

方向としては、ネイティブ・コード向けライブラリの提供はやめて、Web技術を利用して欲しいということのようだ。

iOS

Universal Linksを利用した方法。Twitterアプリケーションがインストールされていない場合はWebブラウザで、インストールされている場合は、Twitterアプリケーションでの投稿となる。

@IBAction func intentTweet(_ sender : Any) {
    let text = "Web Intentの例"
    let encodedText = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    if let encodedText = encodedText,
        let url = URL(string: "https://twitter.com/intent/tweet?text=\(encodedText)") {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

具体的な仕様は以下で説明されている。

このURLに文言をパラメータとして設定してオープンするという仕組みだ。

Twitterアプリケーションがインストールされていない

Web Intent - Twitterアプリなし.png

Twitterアプリケーションがインストールされている

Web Intent - Twitterアプリあり.png

iOSの共有機能を提供するUIActivityViewControllerを利用する方法。Twitterアプリがインストールされていないと候補に現れないだとか、SNS共有っぽくはない。でも、テキストに加え、画像も直に共有できる。

@IBAction func activityTweet(_ sender : Any) {
    let text = "共有機能を利用する"
    let bundlePath = Bundle.main.path(forResource: "brownout", ofType: "jpg")
    let image = UIImage(contentsOfFile: bundlePath!)
    let shareItems = [image, text] as [Any]
    let controller = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
    present(controller, animated: true, completion: nil)
}

共有先を選ぶ

共有機能.png

Twitterを選ぶと、Twitterアプリの投稿画面。画像も扱える。

共有機能 Twitter.png

Android

ボタンと配置する。最近のAndroid Studioは向上している。Xcode並みに開発しやすくなっている。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/intentTweetButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="intent tweet"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/shareCompatButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="ShareCompat"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/intentTweetButton" />

</androidx.constraintlayout.widget.ConstraintLayout>

インテントを利用する方法。TwitterアプリがインストールされていないとWebブラウザで、インストールされているとTwitterアプリが利用される。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 
    val intentTweetButton: Button = findViewById(R.id.intentTweetButton)
    intentTweetButton.setOnClickListener {
        shareTwitter()
    }
}
 
fun shareTwitter() {
    val message = "shareTwitter intent tweet"
    try {
        val sharingIntent = Intent(Intent.ACTION_SEND)
        sharingIntent.setClassName("com.twitter.android", "com.twitter.android.PostActivity")
        sharingIntent.putExtra(Intent.EXTRA_TEXT, message)
        startActivity(sharingIntent)
    }
    catch (e: Exception) {
        Log.e("In Exception", "Comes here")
        val i = Intent()
        i.putExtra(Intent.EXTRA_TEXT, message)
        i.action = Intent.ACTION_VIEW
        i.data = Uri.parse("https://mobile.twitter.com/compose/tweet")
        startActivity(i)
    }
}

OSのWeb Intentと同様な仕組みだ。

intent tweet.png

共有機能を利用する方法。TwitterアプリがインストールされていないとTweetできない。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 
    val shareCompatButton: Button = findViewById(R.id.shareCompatButton)
    shareCompatButton.setOnClickListener {
        shareCompat()
    }
}
 
fun shareCompat() {
    val message = "shareCompat"
    val builder = ShareCompat.IntentBuilder.from(this)
    builder.setChooserTitle("Choose App")
    builder.setText(message)
    builder.setType("text/plain")
    builder.startChooser()
}

共有先を選ぶ

ShareCompat.png

Twitterを選ぶと、Twitterアプリの投稿画面。画像も扱えるはずだが、自分はうまくいかなかった。

ShareCompat tweet.png

ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Tweets - GitHub

https://github.com/murakami/workbook/tree/master/android/Tweets - GitHub

【関連情報】
Cocoa.swift 2019-09

Cocoa.swift

Cocoa勉強会 関東

Cocoa練習帳

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2