• Stars
    star
    242
  • Rank 167,018 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

Swift Reddit API Wrapper

Carthage compatible Version License Platform Build Status

reddift

reddift is Swift Reddit API Wrapper framework, and includes a browser is developed using the framework.

  • Supports OAuth2(is not supported on tvOS currently).
  • Supports multi-accounts.
  • Includes a sample application(iOS only).

Browser

  • It's a typical browser of reddit.com.
  • This application uses "reddift framework" in order to access reddit.com.
  • Includes almost all of functions, such as image thumbnails, browsing comments, search subreddits and so on.
  • If you need more features to this, please send pull requests to me.

reddift-comments reddift-images

Document

How to build

Now, it's under developing. You have to pay attention to use this library.

1. Check out source code.

# check out reddift and its submodules.
> git clone --recursive https://github.com/sonsongithub/reddift.git

Check that these libraries are checked out at each path correctly.

/framework/vendor/HTMLSpecialCharacters
/framework/vendor/MiniKeychain

2. Create application(installed app) at reddit.com

Create new installed app via preference page at reddit.com. And then, check your app's cliend_id and fill out redirect_uri for OAuth2. For example, redirect_uri is set to myapp://response. In following sample, redirect_uri is set to reddift://response.

installedapp

3. Set up reddift_config.json

This JSON file saves application information to use OAuth. Rename reddift_config.json.sample to reddift_config.json. And fill out DeveloperName, redirect_uri and client_id. redirect_uri must be same one you registered at reddit.com. You can check client_id at application tab. reddift generates http's user-agent property using this JSON and application's info.plist.

{
  "DeveloperName": "<YOUR NAME>",
  "redirect_uri": "<YOUR REDIRECT URI>",
  "client_id": "<YOUR ID>"
}

4. Set up your URI on Xcode

In Xcode, set up URL Types in order to receive call back from Safari. Set URL Schemes to redirect_uri that you set at reddit.com. You don't have to include ://response to this form. These URI must be identical. If they are not identical, reddit.com does not authorize your OAuth request. In following sample, URL Schemes is set to reddift.

reddit2

How to build test

1. Register user script app

Test uses Application Only OAuth to remove user interaction from test process. If you want to run tests of reddift, you have to create another "Script" type application(personal use script) at reddit.com.

userscript

2. Fill out test_config.json

At first, rename test_config.json.sample to test_config.json. Fill each following value using above preference pain of reddit.com.

{
  "username": "test user account",
  "password": "test user password",
  "client_id": "test app client ID(must be script type app)",
  "secret": "test app secret"
}

3. Start test

Cmd + U.

How to build browser sample

You have to build dependent frameworks using carthage before building a sample application using Xcode.

# before open xcode project file.
> carthage update --platform iOS

carthage works corretly, you can get following frameworks at each path.

/Carthage/Build/iOS/FLAnimatedImage.framework
/Carthage/Build/iOS/YouTubeGetVideoInfoAPIParser.framework
/Carthage/Build/iOS/UZTextView.framework

And, you get to edit URI types and reddift_config.json as same as the framework.

Create you app.

Get something & Error handling

reddift returns Result<T> object as a result. Get the value or error from Result<T> object. Concretely, you can access either value evaluating enum state like a following code.

// do not use "!" in your code
switch(result) {
case .failure(let error):
    println(error)
case .success(let listing):
    // do something to listing
}

In more detail about this coding style, see "Efficient JSON in Swift with Functional Concepts and Generics".

Create session

At first, you have to implement codes to receive the response of OAuth2 in UIAppDelegate. reddift let you save tokens as a specified name into KeyChain. Specifically, following sample code saves token as user name at reddit.com.

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion:{(result) -> Void in
        switch result {
        case .failure(let error):
            print(error)
        case .success(let token):
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                OAuth2TokenRepository.saveIntoKeychainToken(token, name:token.name)
            })
        }
    })
}

To communicate with reddit.com via OAuth2, you have to create Session object. See following section about getting response or error handling.

let result = OAuth2TokenRepository.restoreFromKeychainWithName(name)
switch result {
case .failure(let error):
    print(error.description)
case .success(let token):
    con.session = Session(token: token)
}

You can get contents from reddit via Session object like following codes.

session?.getList(paginator, subreddit:subreddit, sort:sortTypes[seg.selectedSegmentIndex], timeFilterWithin:.All, completion: { (result) in
    switch result {
    case .failure(let error):
        print(error)
    case .success(let listing):
        self.links.appendContentsOf(listing.children.flatMap{$0 as? Link})
    }
})

Use Application Only OAuth

You can use OAuth2AppOnlyToken when you want to write a code for test or personal script tool(such as CLI). OAuth2AppOnlyToken enabled to access reddit without human action in order to authorize in web browser apps. Do not use Oauth2AppOnlyToken in installed app in terms of security.

OAuth2AppOnlyToken.getOAuth2AppOnlyToken(
    username: username,
    password: password,
    clientID: clientID,
    secret: secret,
    completion:( { (result) -> Void in
    switch result {
    case .failure(let error):
        print(error)
    case .success(let token):
        self.session = Session(token: token)
    }
}))

Further more,

In more detail, See my sample application, test code or Playground code included in this repository.

Playground

You can play with reddift in Playground. In more detail, check reddift.playground package. Before using, you have to copy test_config.json into ./reddift.playground/Resources in order to specify user account and your application informatin because reddift on Playground uses "Application Only OAuth".

playground

Dependency

License

MIT License.

More Repositories

1

CoreAR

AR(Augmented reality) framework for iOS, based on a visual code like ARToolKit
C
253
star
2

PopupView

PopupView for iOS, like UICalloutView. BSD License.
Objective-C
230
star
3

numsw

Swift library like numpy, playgrounds notebook like jupyter.
Swift
134
star
4

AAKeyboard

ASCI Art Keyboard
Objective-C
106
star
5

iOSCameraImageProcessing

Real time image processing framework for iOS
Objective-C
103
star
6

Quartz-Help-Library

Quartz Help Library for iOS, for image processing on iOS.
Objective-C
50
star
7

llvm-tutorial

LLVM Tutorialใ‚’ๅ‹‰ๅผทใ™ใ‚‹ใƒชใƒใ‚ธใƒˆใƒช
C++
45
star
8

HomeConMenu

App to control HomeKit Devices from macOS system
Swift
44
star
9

UZTextView

Clickable and selectable text view for iOS
HTML
40
star
10

OpenCV-Help-Library

OpenCV Help Library for iOS
Objective-C
26
star
11

iCloudSample

Objective-C
22
star
12

EvernoteAPI

Simple Evernote API management class for iOS.
Objective-C
21
star
13

IntroduceCollectionView

Getting started UICollectionView
20
star
14

YouTubeGetVideoInfoAPIParser

Swift Library to parse YouTube streaming data from get_video_info API.
Swift
18
star
15

UZMultipleLayeredPopoverController

Objective-C
17
star
16

museum2tch

2tchๅš็‰ฉ้คจ
Objective-C
16
star
17

HTMLSpecialCharacters

Library to escape/unescape HTML special characters in Swift.
Swift
16
star
18

PlayPixels

Swift Playground Book for learning image processing.
Swift
16
star
19

iCloudFileSharing

Objective-C
13
star
20

iOS_OpenCV_build_script

This is a project for building OpenCV for iOS
Objective-C
12
star
21

SBMeter

This application receives data from the SwitchBot meter via Bluetooth LE and displays it in the menu bar for macOS.
Swift
9
star
22

sonson

sonson's iPhone source codes
Ruby
8
star
23

UZImageCollection

Image collection view controller like Photo.app.
Swift
7
star
24

HandoffSample

Objective-C
6
star
25

SNStatusBarView

Blinking statusbar
Objective-C
6
star
26

AirFollow

Objective-C
5
star
27

llvm_jit_compile

Try to "Just In Time" compile using LLVM.
C++
5
star
28

AnonyFollow

Application to collecting friends of Twitter using anonymous-communication.
Objective-C
5
star
29

RMBluteooth

Bluetooth library for ROMO
Objective-C
4
star
30

hideHere

Objective-C
4
star
31

UZInputCandidateAccessory

Keyboard input accessory view that displays some candidates for a word.
Objective-C
4
star
32

MacCatalystWithAppKit

Build a Mac Catalyst application with AppKit
Swift
4
star
33

CommonCrypto

Framework to include "CommonCrypto.h" for Swift
3
star
34

iOSLegacyCodes

Objective-C
3
star
35

ProvidingDirections

New feature - Providing directions for iOS6
Objective-C
3
star
36

StoreSales

Objective-C
3
star
37

CameraPlaygrounds

Swift Playgrounds Book for image processing programming using iPad's camera.
Swift
3
star
38

swiftodon

2
star
39

ATNDEasy

Objective-C
2
star
40

iOS6_2PainViewController

Best example of container view to implement 2 pain views in one view controller.
Objective-C
2
star
41

StudyWatch

Swift
2
star
42

WaveFrontObjectLoader

I want to improve the good project, WaveFrontObjectLoader. Original project is http://code.google.com/p/iphonewavefrontloader/.
Objective-C
2
star
43

Markdown

Convert text into html that looks like github.
Perl
2
star
44

SoftwareDesignSonson

source code for monthly Software Design Magazine
Objective-C
2
star
45

SNProxyDetector

Class to detect system proxy setting.
Objective-C
1
star
46

auto.gitconfig.proxy

Automatic onfiguration gitconfig' proxy setting for OSX
Shell
1
star
47

SNReachability

Network reachability check class for iOS
Objective-C
1
star
48

SweepDesk

Temporarily hides desktop files.
Swift
1
star
49

InspectCoreText

Objective-C
1
star
50

testFoldr

foldr implementaion in Swift
Swift
1
star
51

midi-swift-code

Swift code to use CoreMIDI
Swift
1
star
52

UntarLight

A light and elementary library to extract the structure and each files in a tar file in Swift
Swift
1
star
53

zipr

Reader for a zip file including only image files.
Swift
1
star
54

spbuilder

Swift Playgrounds Book Builder
Swift
1
star
55

F2-210

Scripts, documents and config files for F2-210.
Shell
1
star
56

TodayWidgetSample

Objective-C
1
star
57

zipreview

Quick Look Plugins for an archive file.
Swift
1
star
58

CloudKitSample

Objective-C
1
star
59

StringIconv

Decode bytes array to String using iconv.
Swift
1
star