6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【iOS】ツイートをサクッと実装【Swift3.0】

Last updated at Posted at 2017-01-10

Apple純正のソーシャルライブラリを使ってツイート処理を実装してみます。

見本
IMG_0792.png

実装

1. Social.frameworkを追加

1.png

2. サンプルソース

ツイートのミニマムサンプルです。実行すると画面の真ん中にツイートボタンが表示され、ボタンクリックで見本のようなツイート入力画面が出現します。


//
//  ViewController.swift
//  Tweet
//
//

import UIKit
import Social

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        // ツイートボタン
        let button = UIButton(frame: CGRect(x:0,y:0,width:200,height:30))
        button.center = view.center
        button.setTitle("tweet", for: .normal)
        button.layer.backgroundColor = UIColor.red.cgColor
        button.addTarget(self, action: #selector(ViewController.tweet), for: .touchUpInside)
        view.addSubview(button)
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tweet() {
        
        // ツイート処理が可能かチェック
        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) {
            // make controller to share on twitter
            let slc = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            
            slc?.setInitialText("ツイートしちゃうよ!")
            slc?.add(UIImage(named:"leako.png"))
            
            // ツイート入力画面表示
            present(slc!, animated: true, completion: {
            })
            
            // 事後処理
            slc?.completionHandler = {
                (result:SLComposeViewControllerResult) -> () in
                switch (result) {
                    
                // 投稿した
                case SLComposeViewControllerResult.done:
                    print("tweeted")
                
                // キャンセルした
                case SLComposeViewControllerResult.cancelled:
                    print("tweet cancel")
                    
                }
            }
        } else {
            print("can not tweet")
        }
    }
}

これだけです。簡単です。ユーザの動作別(投稿かキャンセル)に処理を定義しておくことが可能です。


public enum SLComposeViewControllerResult : Int {
    
    case cancelled

    case done
}
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?