-
Notifications
You must be signed in to change notification settings - Fork 448
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.
Twitter Kit is available for download from the installation
page, or can be installed via the
TwitterKit
pod for CocoaPods.
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:
- Create an app with read-write permissions
- 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. - Ensure you check “Allow this application to be used to sign in with Twitter” in the settings.
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 TWTRTwitter.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
See the getting started and log in with Twitter documentation for full details.
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.
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:
TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
if let sess = session {
print("signed in as \(sess.userName)");
} else {
print("error: \(error.localizedDescription)");
}
}
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
TWTRTwitter.sharedInstance().sessionStore.session()
to get
the current authorized session rather than triggering a new log-in flow.
TWTRTwitter.sharedInstance().sessionStore.hasLoggedInUsers()
lets you test if there are any sessions in your app.
See log in with Twitter for more information.
Twitter Kit provides a composer for sharing links, images, and video.
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.
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.
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 = TWTRTwitter.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.