• Stars
    star
    111
  • Rank 314,510 (Top 7 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 3 years ago
  • Updated 12 months ago

Reviews

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

Repository Details

๐Ÿฆ An async Swift library for the Twitter v2 API ๐Ÿšง WIP

Twift

Twitter API v2 badge Documentation Coverage Run Tests Build Demo App

Twift is an asynchronous Swift library for the Twitter v2 API.

  • No external dependencies
  • Fully async
  • Full Swift type definitions/wrappers around Twitter's API objects

Quick Start Guide

New Twift instances must be initiated with either OAuth 2.0 user authentication or an App-Only Bearer Token:

// OAuth 2.0 User Authentication
let oauthUser: OAuth2User = OAUTH2_USER
let userAuthenticatedClient = Twift(oauth2User: oauthUser, onTokenRefresh: saveUserCredentials)

// App-Only Bearer Token
let appOnlyClient = Twift(appOnlyBearerToken: BEARER_TOKEN)

You can authenticate users with Twift.Authentication().authenticateUser():

var client: Twift?

do {
  let oauthUser = try await Twift.Authentication().authenticateUser(
    clientId: TWITTER_CLIENT_ID,
    redirectUri: URL(string: TWITTER_CALLBACK_URL)!,
    scope: Set(OAuth2Scope.allCases)
  )
  
  client = Twift(oauth2User: oauthUser, onTokenRefresh: saveUserCredentials)
  
  // It's recommended that you store your user auth tokens via Keychain or another secure storage method.
  // OAuth2User can be encoded to a data object for storage and later retrieval.
  saveUserCredentials(oauthUser) // Saves the data to Keychain, for example
} catch {
  print(error.localizedDescription)
}

Once initiated, you can begin calling methods appropriate for the authentication type:

do {
  // User objects always return id, name, and username properties,
  // but additional properties can be requested by passing a `fields` parameter
  let authenticatedUser = try await userAuthenticatedClient.getMe(fields: [\.profilePhotoUrl, \.description])
  
  // Non-standard properties are optional and require unwrapping
  if let description = authenticatedUser.description {
    print(description)
  }
} catch {
  print(error.localizedDescription)
}

Posting Tweets supports text and polls. Media methods are OAuth 1.0a only and the API may change significantly when Twitter's v2 API adds new media endpoints.

do {
  let textOnlyTweet = MutableTweet(text: "This is a test Tweet")
  try await twitterClient.postTweet(textOnlyTweet)
  
  let poll = try MutablePoll(options: ["Soft g", "Hard g"])
  let tweetWithPoll = MutableTweet(text: "How do you pronounce 'gif'?", poll: poll)
  try await twitterClient.postTweet(tweetWithPoll)
} catch {
  print(error)
}

Requirements

To be completed

Documentation

You can find the full documentation in this repo's Wiki (auto-generated by SwiftDoc).

Quick Tips

Disambiguating List

If you use Twift with SwiftUI, sooner or later you might run into the problem of needing to disambiguate Twift.List from SwiftUI.List. It is recommended that you assign a typealias in a file that doesn't import SwiftUI to disambiguate between the types:

import struct Twift.List

typealias TwitterList = Twift.List

Typical Method Return Types

Twift's methods generally return TwitterAPI[...] objects containing up to four properties:

  • data, which contains the main object(s) you requested (e.g. for the getUser endpoint, this contains a User)
  • includes, which includes any expansions you request (e.g. for the getUser endpoint, you can optionally request an expansion on pinnedTweetId; this would result in the includes property containing a Tweet)
  • meta, which includes information about pagination (such as next/previous page tokens and result counts)
  • errors, which includes an array of non-failing errors

All of the methods are throwing, and will throw either a TwiftError, indicating a problem related to the Twift library (such as incorrect parameters passed to a method) or a TwitterAPIError, indicating a problem sent from Twitter's API as a response to the request.

Fields and Expansions

Many of Twift's methods accept two optional parameters: fields and expansions. These parameters allow you to request additional fields (properties) on requested objects, as well as expansions on associated objects. For example:

// Returns the currently-authenticated user
let response = try? await userAuthenticatedClient.getMe(
  // Asks for additional fields: the profile image URL, and the user's description/bio
  fields: [\.profileImageUrl, \.description],
  
  // Asks for expansions on associated fields; in this case, the pinned Tweet ID.
  // This will result in a Tweet on the returned `TwitterAPIDataAndIncludes.includes`
  expansions: [
    // Asks for additional fields on the Tweet: the Tweet's timestamp, and public metrics (likes, retweets, and replies)
    .pinnedTweetId([
      \.createdAt,
      \.publicMetrics
    ])
  ]
)

// The user object
let me = response?.data

// The user's pinned Tweet
let tweet = response?.includes?.tweets.first

More Repositories

1

Toast

๐Ÿž A highly-customizable, responsive (S)CSS grid
CSS
2,000
star
2

Baseline.js

A simple jQuery plugin for restoring vertical baselines thrown off by odd image sizes
JavaScript
699
star
3

basehold.it

A quick, painless, Javascript-free baseline overlay.
TypeScript
537
star
4

daneden.me

๐Ÿก This is my website. There are many like it, but this one is mine.
MDX
336
star
5

sublime-css-completions

A more complete library of CSS completions for Sublime Text
283
star
6

Zeitgeist

๐Ÿ‘ An iOS app for keeping an eye on your Vercel deployments
Swift
190
star
7

photos.daneden.me

๐Ÿ“ธ A React.js-based gallery of some of my favorite photos
TypeScript
146
star
8

PHP-Functions

Some PHP functions that are pretty damn useful
PHP
107
star
9

dotfiles

๐Ÿ’ป These are my dotfiles. There are many like them, but these ones are mine.
Shell
81
star
10

Solstice

๐ŸŒ… An app that tells you how the daylight is changing
Swift
76
star
11

sketch-collapse-all

A Sketch plugin/shortcut to collapse all groups and artboards
JavaScript
61
star
12

design-systems-office-hours-playbook

A playbook for running Design Systems office hours or attending them as a Design System representative. Use this as a template for making your own company Design Systems office hours playbook!
57
star
13

sketch-align-layers

Align layers by edges and centers in Sketch
JavaScript
46
star
14

gifme

MVP do-it-yourself Giphy
JavaScript
43
star
15

Broadcast

๐Ÿ—ฃ A write-only Twitter client
Swift
41
star
16

ohshitbot

A Twitter bot that panics
JavaScript
33
star
17

sketch-navigate-artboards

Navigate artboards in Sketch
JavaScript
31
star
18

who-would-win

๐ŸฅŠ A Twitter bot that pits emoji against one another
JavaScript
27
star
19

daneden-og-image-generator

An open graph image generator for my website, daneden.me
TypeScript
25
star
20

processing-deepjoy

Processing
21
star
21

next-ssr-example

JavaScript
19
star
22

ia-writer-zettelkasten

๐Ÿ“ An AppleScript service for creating new Zettelkasten-esque notes in iA writer
15
star
23

art.daneden.me

A home for generative art
JavaScript
15
star
24

sketch-replace-layer

๐Ÿ’Ž A Sketch plugin to replace selected layer(s) with copied content/layer(s)
JavaScript
14
star
25

kindle-airtable-sync

A JavaScript/Node utility to publish Kindle Highlights to an Airtable base
JavaScript
13
star
26

processing-flow-field

Processing
13
star
27

kindle-highlights

A Vercel/Next.js app to render my Kindle highlights
TypeScript
12
star
28

enable-automerge-action

๐Ÿค– A GitHub action that enables automerge for pull requests opened by a specified author
TypeScript
11
star
29

muffler

A macOS menu bar app to quickly toggle your microphone and/or video for Zoom and BlueJeans
Swift
11
star
30

shortener

A Netlify-powered personal URL shortener
10
star
31

eloquent-js

My playground for going through the exercises in the book โ€œEloquent JavaScriptโ€
JavaScript
10
star
32

justmytype

CSS
9
star
33

sketch-plugins

๐Ÿ’Ž A collection of Sketch plugins authored and maintained by myself
9
star
34

pipify

HTML
9
star
35

Tumblr-Prototype

Homework for week 5 of the CodePath course
Swift
8
star
36

Dropbox-Prototype

A Dropbox app prototype built during the CodePath course
Swift
8
star
37

processing-sandlines

Processing
8
star
38

goldenhour

A minisite for my favorite โ€œgolden hourโ€ photos
HTML
7
star
39

2017-music

JavaScript
7
star
40

subtweet

A Twitter bot that tweets randomly selected [SOUND EFFECTS] from subtitles
JavaScript
7
star
41

Converge

A unit conversion widget for macOS
Swift
6
star
42

serious-games

PHP
6
star
43

gantter

TypeScript
6
star
44

Wayfinder-iOS

An iOS-native version of Wayfinder, built during the CodePath iOS for Designers course
Swift
6
star
45

Mailbox-Prototype

Homework for week 3 of the CodePath course
Swift
6
star
46

react-coin-toss

A simple React application that simulates tossing a coin to visualise the average result
JavaScript
6
star
47

Jukebox-iOS

Swift
5
star
48

nounsbot

Pick some nouns. Tweet them.
JavaScript
5
star
49

Carousel-Prototype

Homework for week 2 of the CodePath course
Swift
5
star
50

Facebook-Prototype

Homework for week 4 of the CodePath course
Swift
5
star
51

gatsby-remark-smallcaps

JavaScript
5
star
52

language-sketchplugin

Correct Atom syntax highlighting for .sketchplugin files
CoffeeScript
5
star
53

nextjs-data-fetching

TypeScript
4
star
54

Tinder-Prototype

Swift
4
star
55

2018-music

Photos taken in Oakland in 2018
JavaScript
4
star
56

random-music-playlist

๐Ÿ”€ A macOS service script that plays a random playlist in Apple Music.
4
star
57

processing-rotator

Processing
4
star
58

iOS-Tips

A simple tip calculator written in Swift, with the help of Codepath.
Swift
4
star
59

Emery

๐Ÿ’… A simple app for previewing nail art
Swift
3
star
60

eslint-plugin-daneden

JavaScript
3
star
61

de-gifs-client

A Next.js client for de-gifs.netlify.com
TypeScript
3
star
62

gifme-ios

An iOS app for gif.daneden.me
Swift
3
star
63

Untones

Occasional, delightful ringtones.
CSS
3
star
64

typography.js

Automatic class-writing for web typography tweaks
JavaScript
3
star
65

dtebot

A Markov-chain Twitter bot
Python
3
star
66

processing-rorschach

Processing
3
star
67

jukebox

TypeScript
3
star
68

markov-js

A naive Markov chain implementation in JavaScript
JavaScript
3
star
69

Modal-Transitions

Swift
3
star
70

handy

A simple golf handicap calculator for the Abergele Golf Club
TypeScript
2
star
71

daneden.github.io

HTML
2
star
72

who-would-win-bot

๐ŸฅŠ A Twitter bot that pits emoji against one another
TypeScript
2
star
73

raggedwrite

CSS
2
star
74

jamesgosling

Ruby
1
star
75

rando

๐ŸŽฒ A simple React app that allows you to enter a list of (locally-stored) items and pick one at random.
TypeScript
1
star
76

daneden.me.old

An archived version of my siteโ€™s repo going as far back as 2013.
TypeScript
1
star
77

wwwb-leaderboard

TypeScript
1
star