Migrating from iOS Social Framework

iOS 11 no longer supports using Twitter through the built-in social framework. Instead, you can use Twitter Kit 3 to Tweet, log in users, and use the Twitter API. The following guide shows how to migrate your old code.

Get Twitter Kit 3

Download Twitter Kit, or install via CocoaPods

Twitter Kit is available for download from the installation page, or can be installed via the TwitterKit pod for CocoaPods.

Register an app in the Twitter apps dashboard

To use Twitter features in your app, you need to create an application API key. Visit the Twitter app dashboard to do so. To ensure parity with the the previous iOS functionality:

  1. Create an app with read-write permissions
  2. For legacy reasons, you must set a callback URL to enable user authorization. Use https://example.com as if you don’t intend to use a web callback for this app.
  3. Ensure you check “Allow this application to be used to sign in with Twitter” in the settings.

Add Twitter Kit initialization code to your app delegate

Once the SDK is installed and your app keys are registered, you need to add three hooks for the app to use all features of Twitter Kit.

Add twitterkit-<yourConsumerKey> as a URL scheme for your app — this allows Twitter for iOS and Safari to be used to authorize users. In your Info.plist:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>twitterkit-{yourConsumerKey}</string>
    </array>
  </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
    <string>twitterauth</string>
</array>

Add the corresponding handler to application:openURL:options: to receive log in credentials from those external applications:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  if Twitter.sharedInstance().application(app, open: url, options: options) {
    return true
  }
  // Your other open URL handlers follow […]
}

Finally, call Twitter.start() in your application delegate application:didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  Twitter.sharedInstance().start(withConsumerKey: "example-hPpFPVQ64pThkM0", consumerSecret: "exmaple-ovAqziZzzHpU5F163Qg9mj")
  return true
}

See the getting started and log in with Twitter documentation for full details.

Log In with Twitter

For users to log in to your app, Twitter Kit provides a APIs for invoking authorization and even a fully encapsulated log in button component. Twitter Kit will automatically use the Twitter for iOS app from which users can pick any of their Twitter accounts, and fall back to web-based OAuth for users who don’t have Twitter installed.

Use Twitter.logIn instead of ACAccountStore.requestAccessToAccounts

In the social framework accounts were managed globally through ACAccountStore. Now, each app is responsible for its own Twitter sessions. Twitter Kit makes it easy to authorize users using the Twitter for iOS app and OAuth, so the amount of code you need remains similar.

With ACAccountStore you might write:

let account = ACAccountStore()
let accountType = account.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)

account.requestAccessToAccounts(with: accountType, options: nil, completion: {(success, error) in
  if success {
    if let twitterAccount = account.accounts(with: accountType).last as? ACAccount {
      print("signed in as \(twitterAccount.userame)");
    }
  }
})

With Twitter Kit:

Twitter.sharedInstance().logIn(completion: { (session, error) in
  if let sess = session {
    print("signed in as \(sess.userName)");
  } else {
    print("error: \(error.localizedDescription)");
  }
}

Use TWTRSessionStore instead of ACAccountStore.accounts

When a user authorizes your app to use their account, Twitter Kit will save the session for you. After the first log in you can use Twitter.sharedInstance().sessionStore.session() to get the current authorized session rather than triggering a new log-in flow.

Twitter.sharedInstance().sessionStore.hasLoggedInUsers() lets you test if there are any sessions in your app.

See log in with Twitter for more information.

Tweeting

Twitter Kit provides a composer for sharing links, images, and video.

Use TWTRComposer instead of SLComposeViewController

SLComposerViewController enabled easily composing Tweets with text, URLs and images:

if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
  let composer = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
  composer.setInitialText("Hello Twitter!")
  composer.addImage(UIImage(named: "hello"))
  composer.addURL(URL(string: "https://dev.twitter.com"))
  self.presentViewController(socialController, animated: true, completion: nil)
}

Twitter Kit provides a lightweight TWTRComposer with the same capabilities, and encapsulates authorizing users if your app does not have explicit log in functionality:

let composer = TWTRComposer()
composer.setText("Hello Twitter!")
composer.setImage(UIImage(named: "hello"))
composer.setUrl(URL(string: "https://dev.twitter.com"))
composer.show(from: self, completion: nil)

For advanced Tweet composition, including posting video, see the full TWTRComposeViewController documentation in compose Tweets.

Using the Twitter API

After authorizing users, Twitter Kit provides means to make requests to the Twitter API to build full-featured applications. Follow the instructions above to update authorization of users, and then use the API Client handle making OAuth signed requests to any Twitter API endpoint.

Use TWTRAPIClient instead of SLRequest

To make a request to the Twitter API, you might previously have written this:

let account = ACAccountStore()
let accountType = account.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)

account.requestAccessToAccounts(with: accountType, options: nil, completion: {(success, error) in
    if success {
        if let twitterAccount = account.accounts(with: accountType).last as? ACAccount
       let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
          let params = ["id": "20"]

          let request = SLRequest(forServiceType: SLServiceTypeTwitter,
      requestMethod: SLRequestMethod.GET,
      URL: URL(string: statusesShowEndpoint),
      parameters: params)
           request?.account = twitterAccount
       request?.perform(handler: {(responseData, urlResponse, error) in
                if let err = error {
                    print("Error : \(err.localizedDescription)")
                } else {
                    print("The first Tweet: \(responseData)")
                }
            })
        }
    }
})

With Twitter Kit, you perform the same call like this:

if let twitterAccountId = Twitter.sharedInstance().sessionStore.session()?.userID {
  let client = TWTRAPIClient(userID: twitterAccountId)
  let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
  let params = ["id": "20"]
  var clientError : NSError?

  let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)

  client.sendTwitterRequest(request) { (response, responseData, error) -> Void in
    if let err = error {
        print("Error: \(err.localizedDescription)")
    } else {
      print("The first Tweet: \(responseData)")
    }
  }
} else {
  // Not logged in
}

Twitter Kit also includes higher level helpers for fetching Tweets and user objects. Read more in the full accessing the REST API documentation.


Twitter Kit provides functionality beyond what was available in iOS. Views for rendering Tweets and timelines take care of displaying Tweets in your app, and support for guest authorization allows you to display content to users before taking them through authorization.

Read about Twitter Kit in the full documentation, explore classes use in the appledocs, and please feel free to ask questions in the developer forums.