Swift library for the Twitter API v1 and v2.
Please see this issue for the progress of the API implementation.
Issue やコメントは日本語でも大丈夫です。
Unfortunately, I couldn't find any active Twitter API library for Swift at the moment.
So, I decided to create one.
- No dependencies
You can limit the scope of available APIs depending on your application. This is useful if your app only supports v1, or if you want to limit access to the API. Currently, scoping according to Twitter's App permissions is not yet implemented.
// The most common usage.
// For OAuth 1.0a
letclient=TwitterAPIClient(.oauth10a(.init(
consumerKey:"",
consumerSecret:"",
oauthToken:"",
oauthTokenSecret:"")))
// For OAuth 2.0 client
letclient=TwitterAPIClient(.oauth20(.init(
clientID:"",
scope:[],
tokenType:"",
expiresIn:0,
accessToken:"",
refreshToken:"")))
client.v1.someV1API()
client.v2.someV2API()
// V1 only client
letv1Client= client.v1
v1Client.someV1API()
// V2 only client
letv2Client= client.v2
v2Client.someV2API()
// DM only client
letdmClient= client.v1.directMessage
dmClient.someDM_APIs()
// Each API can be accessed flatly or by individual resource.
// Flat.
letclient.v1.allV1_APIs()
// Individual resources.
letclient.v1.tweet.someTweetAPIs()letclient.v1.directMessage.someDM_APIs()Please see "HowDoIAuthenticate.md"
And the following sample project includes a sample authentication.
Please see "HowToDecodeResponse.md"
TwitterAPIKit can be used on Linux, but cannot be merged into the main branch because it cannot run tests.
If you want to use it on Linux, use THIS BRANCH.
This sample project contains examples of how to authenticate with OAuth 1.0a User Access Tokens (3-legged OAuth flow) and OAuth 2.0 Authorization Code Flow with PKCE.
letconsumerKey=""letconsumerSecret=""letoauthToken=""letoauthTokenSecret=""letclient=TwitterAPIClient(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
oauthToken: oauthToken,
oauthTokenSecret: oauthTokenSecret
)
client.v1.getShowStatus(.init(id:"status id"))
// Already serialized using "JSONSerialization.jsonObject(with:, options:)".
.responseObject(){ response in}.responseObject(queue:.global(qos:.default)){ response in}
// Already decoded using JSONDecoder.
.responseDecodable(type:Entity.self, queue:.global(qos:.default)){ response in}.responseDecodable(type:Entity.self){ response in}
// Unprocessed data
.responseData(){ response in /* Run in .main queue */ }.responseData((queue:.global(qos:.default)){ response in /* Run in .global(qos: .default) queue */ }
// !! A `prettyString` is provided for debugging purposes. !!
print(response.prettyString)
result.map((Success)-> NewSuccess)
result.tryMap((Success) throws -> NewSuccess)
result.mapError((TwitterAPIKitError)-> TwitterAPIKitError>)
result.success // Success?
result.error // TwitterAPIKitError?
response.rateLimit
// Use result
do{letsuccess=try response.result.get()print(success)}catchlet error{print(error)}}letrefresh=tryawait client.refreshOAuth20Token(type:.confidentialClient(clientID:"", clientSecret:""), forceRefresh:true)
// let refresh = try await client.refreshOAuth20Token(type: .publicClient, forceRefresh: true)
// The authentication information in the Client is also updated, so there is no need to recreate a new instance of the Client.
if refresh.refreshed {storeToken(refresh.token)}
// Or
client.refreshOAuth20Token(type:.publicClient, forceRefresh:true){ result indo{letrefresh=try result.get()if refresh.refreshed {storeToken(refresh.token)}}catch{}}
// Notification
NotificationCenter.default.addObserver(self,
selector: #selector(didRefreshOAuth20Token(_:)),
name:TwitterAPIClient.didRefreshOAuth20Token,
object:nil)@objcfunc didRefreshOAuth20Token(_ notification:Notification){guardlet token = notification.userInfo?[TwitterAPIClient.tokenUserInfoKey]as?TwitterAuthenticationMethod.OAuth20else{fatalError()}print("didRefreshOAuth20Token", didRefreshOAuth20Token, token)store(token)}The class of each request can be inherited to create subclasses. This is why it is declared as an open class instead of a struct.
This is intended so that when new parameters are added due to changes in the Twitter API, you can handle them yourself without waiting for the library to be updated.
// example
classCustomListsListRequestV1:GetListsListRequestV1{letcustom:Stringoverridevarparameters:[String:Any]{varp= super.parameters
p["custom"]= custom
return p
}init(custom:String, user:TwitterUserIdentifierV1, reverse:Bool?=.none){self.custom = custom
super.init(user: user, reverse: reverse)}}It is also possible to create an encapsulated custom request class.
classCapsuledListsListRequestV1:GetListsListRequestV1{init(){
super.init(user:.userID("100"), reverse:true)}}This method is intended to be used when the library does not yet support Twitter's new API.
- You can customize the request yourself.
- You can use
session.send(TwitterAPIRequest,completionHandler:)to send the request.
classYourCustomRequest:TwitterAPIRequest{
// write code...
}letconsumerKey=""letconsumerSecret=""letoauthToken=""letoauthTokenSecret=""letclient=TwitterAPIClient(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
oauthToken: oauthToken,
oauthTokenSecret: oauthTokenSecret
)letrequest=YourCustomRequest()
client.session.send(request)}Task{letresult=tryawait client.v1.timeline.getHomeTimeline(.init()).responseData // or responseObject or response responseDecodable(type: Hoge.self)
print(result.prettyString)}- Support API v1 endpoint : 85% completed (Commonly used APIs are 100% supported.)
- Support API v2 endpoint: 100% completed (Except for Lab)
- Swift Concurrency (Experimental)
- Document