• This repository has been archived on 30/Jun/2023
  • Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 3 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swift library for the Twitter API v1 and v2 🍷

TwitterAPIKit

Swift library for the Twitter API v1 and v2.

Swift Standard v2 codecov

Please see this issue for the progress of the API implementation.

Issue やコメントは日本語でも大丈夫です。


Motivation

Unfortunately, I couldn't find any active Twitter API library for Swift at the moment.

So, I decided to create one.

Policy

  • No dependencies

API Structures

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
let client = TwitterAPIClient(.oauth10a(.init(
            consumerKey: "",
            consumerSecret: "",
            oauthToken: "",
            oauthTokenSecret: ""
        )))
// For OAuth 2.0 client
let client = TwitterAPIClient(.oauth20(.init(
            clientID: "",
            scope: [],
            tokenType: "",
            expiresIn: 0,
            accessToken: "",
            refreshToken: ""
        )))

client.v1.someV1API()
client.v2.someV2API()

// V1 only client
let v1Client = client.v1
v1Client.someV1API()

// V2 only client
let v2Client = client.v2
v2Client.someV2API()

// DM only client
let dmClient = client.v1.directMessage
dmClient.someDM_APIs()

// Each API can be accessed flatly or by individual resource.

// Flat.
let client.v1.allV1_APIs()

// Individual resources.
let client.v1.tweet.someTweetAPIs()
let client.v1.directMessage.someDM_APIs()

How do I authenticate?

Please see "HowDoIAuthenticate.md"

And the following sample project includes a sample authentication.

https://github.com/mironal/TwitterAPIKit-iOS-sample

How to decode response

Please see "HowToDecodeResponse.md"

Linux support (experimental)

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.

Example

Projects

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.

Basic

    let consumerKey = ""
    let consumerSecret = ""
    let oauthToken = ""
    let oauthTokenSecret = ""

    let client = 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 {
            let success = try response.result.get()
            print(success)
        } catch let error {
            print(error)
        }
    }

Refresh OAuth 2.0 Token

let refresh = try await 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 in
    do {
        let refresh = try result.get()
        if refresh.refreshed {
            storeToken(refresh.token)
        }
    } catch {

    }
}

// Notification

NotificationCenter.default.addObserver(
    self,
    selector: #selector(didRefreshOAuth20Token(_:)),
    name: TwitterAPIClient.didRefreshOAuth20Token,
    object: nil
)

@objc func didRefreshOAuth20Token(_ notification: Notification) {
    guard let token = notification.userInfo?[TwitterAPIClient.tokenUserInfoKey] as? TwitterAuthenticationMethod.OAuth20 else {
        fatalError()
    }
    print("didRefreshOAuth20Token", didRefreshOAuth20Token, token)
    store(token)
}

Custom Request class

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
class CustomListsListRequestV1: GetListsListRequestV1 {

    let custom: String

    override var parameters: [String: Any] {
        var p = 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.

class CapsuledListsListRequestV1: GetListsListRequestV1 {
    init() {
        super.init(user: .userID("100"), reverse: true)
    }
}

Low level api

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.
    class YourCustomRequest: TwitterAPIRequest {
        // write code...
    }


    let consumerKey = ""
    let consumerSecret = ""
    let oauthToken = ""
    let oauthTokenSecret = ""

    let client = TwitterAPIClient(
        consumerKey: consumerKey,
        consumerSecret: consumerSecret,
        oauthToken: oauthToken,
        oauthTokenSecret: oauthTokenSecret
    )

    let request = YourCustomRequest()
    client.session.send(request)
}

Swift Concurrency (experimental)

Task {
    let result = try await client.v1.timeline.getHomeTimeline(.init()).responseData // or responseObject or response responseDecodable(type: Hoge.self)

    print(result.prettyString)
}

Stream API

TODO

  • 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

More Repositories

1

electron-oauth-helper

Easy to use helper library for OAuth1 and OAuth2.
TypeScript
56
star
2

arduinode

Node-Arduino-General-IO
JavaScript
28
star
3

TwitterAPIKit-iOS-sample

Swift
9
star
4

GlacierTools

開発停止。
Java
9
star
5

tw-activity

A library for the Twitter Account Activity API.
TypeScript
7
star
6

ShortHandAlert

A helpful UIAlertController extension and Builder for the slothful human.
Swift
6
star
7

iOS-Bluetooth-ESP32-WiFi

[WIP] Securely send WiFi password to ESP 32 using iOS and Bluetooth.
C++
5
star
8

Zakkuri

A rough goal management app.
Swift
4
star
9

rails-dev-on-centos6

CentOSでrailsの開発環境を構築するVagrantfile
Ruby
4
star
10

VuforiaExternalCameraSample

A sample of Vuforia ImageTarget detection without real camera. This uses locally stored images as camera images.
C#
4
star
11

NowPlayingFormatter

NowPlayingFormatter is a very smart formatter library for MPMediaItem written by Swift.
Swift
3
star
12

mencha

Cloud 感情セイスモグラム 😀 😐 😲 😫
JavaScript
3
star
13

AsyncImageBench

Swift
2
star
14

raccoon

選択した issue をリストアップ -> 選択 -> 洗濯 -> アライグマ -> Raccoon
JavaScript
2
star
15

AndroidLogSender

AndroidLogSender
Java
2
star
16

BotHub

Github の WebHook を受け取って何かする奴を簡単に書くためのミドルウェア ヾ(・∀・)ノダー
JavaScript
1
star
17

validate-ts

The object validator for TypeScript.
TypeScript
1
star
18

Shirase

TypeScript
1
star
19

firebase-tw-webhook

A example project for Twitter Activity API Webhook.
HTML
1
star
20

ghp

A command line tool for GitHub Projects.
TypeScript
1
star
21

issue-lint

A linter for GitHub issue (under PoC).
TypeScript
1
star
22

chlorogenic

Let's organize your GitHub projects of multiple repositories.
TypeScript
1
star
23

awesome-health-checker

TypeScript
1
star
24

Learn-Swift

Objective-C
1
star
25

outdated

A GUI that offers a visual representation the dependence you manage with any package manager.
TypeScript
1
star
26

ReplyYanashe

ReplyYanashe
Java
1
star
27

snippet

snippet
C
1
star