LoginSignup
14
14

More than 5 years have passed since last update.

SwiftでTwitterタイムラインを取得する

Last updated at Posted at 2016-10-13

はじめに

まだ、Swift3に移行の前にSwiftをまともに触れない半年経過した情弱iOSエンジニアです。
この記事はSwift2.2で書かれています!

環境

  • OS X 10.11.6
  • Xcode 7.3.1
  • 夜のテンション

前提

Social.frameworkAccounts.framework を追加しておく

ViewController.swift
import UIKit
import Social
import Accounts

class ViewController: UIViewController {

    var accountStore = ACAccountStore()
    var twitterAccount: ACAccount?

    override func viewDidLoad() {
        super.viewDidLoad()
        getTwitterAccounts()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    private func getTwitterAccounts() {
        let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
        accountStore.requestAccessToAccountsWithType(accountType, options: nil) { [weak self] (granted:Bool, error:NSError?) -> Void in
            if error != nil {
                print(error)
                return
            }

            if !granted {
                print("Use of the Twitter account is not allowed")
                return
            }

            if let unwrapSelf = self {
                let accounts = unwrapSelf.accountStore.accountsWithAccountType(accountType) as! [ACAccount]
                if accounts.count == 0 {
                    print("Add Twitter accounts in the Settings app")
                    return
                }

                unwrapSelf.showAccountSelectSheet(accounts)
            }
        }
    }

    private func showAccountSelectSheet(accounts: [ACAccount]) {

        let alert = UIAlertController(title: "Twitter",
                                      message: "Choose an account",
                                      preferredStyle: .ActionSheet)


        for account in accounts {
            alert.addAction(UIAlertAction(title: account.username,
                style: .Default,
                handler: { [weak self] (action) -> Void in
                    if let unwrapSelf = self {
                        unwrapSelf.twitterAccount = account
                        unwrapSelf.getTimeline()
                    }
            }))
        }

        alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

        self.presentViewController(alert, animated: true, completion: nil)
    }

    private func getTimeline() {
        let URL = NSURL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json?count=200")
        let request = SLRequest(forServiceType: SLServiceTypeTwitter,
                                requestMethod: .GET,
                                URL: URL,
                                parameters: nil)
        request.account = twitterAccount

        request.performRequestWithHandler { (responseData, response, error) -> Void in
            if error != nil {
                print(error)
            } else {
                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(responseData,
                        options: .AllowFragments)
                    for tweet in result as! [AnyObject] {
                        print(tweet["text"] as! String)
                    }
                }  catch let error as NSError {
                    print(error)
                }
            }
        }
    }
}

最後に

なぜかパラメータに ["count": 200] と設定してもデフォルトの20件(?)しか取得できなかった。やり方が違うのかな?

14
14
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
14
14