reddift

reddift is API wrapper for swift(for iOS).

  • Supports OAuth2(and DOES NOT support Cookie-authentication).
  • Supports multi-accounts.
  • Includes a sample application(iOS only).

sc02  sc01

Document

See cocoapods.

How to build

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

1. 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.

installedapp

2. 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.

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

3. Set up your URI on Xcode

In Xcode, register URL Type which uses redirect_uri in order to receive call back from Safari. These URI must be identical. If they are not identical, reddit.com does not authorize your OAuth request.

reddit2

Getting started

In more detail, See the sample application code included in reddift.

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 let .Failure:
            println(result.error)
        case let .Success:
            if let token = result.value as OAuth2Token? {
                token.getProfile({ (result) -> Void in
                    switch result {
                    case let .Failure:
                        println(result.error)
                    case let .Success:
                        if let profile = result.value as? Account {
                            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                                OAuth2TokenRepository.saveIntoKeychainToken(token, name:profile.name)
                            })
                        }
                    }
                })
            }
        }
    })
}

To communicate with reddit.com via OAuth2, you have to create Session object.

let result = OAuth2TokenRepository.restoreFromKeychainWithName(name)
switch(result) {
case .Failure:
    println(result.error!.description)
case .Success:
    if let token = result.value {
        con.session = Session(token: token)
    }
}

Get something & Error handling

You can get contents from reddit via Session object like following codes. reddift returns Result<T> object as a result. In more detail about this coding style, see “Efficient JSON in Swift with Functional Concepts and Generics”.

session?.getList(paginator, sort:sortType, subreddit:subreddit, completion: { (result) in
    switch result {
    case let .Failure:
        println(result.error)
    case let .Success:
        println(result.value)
        if let listing = result.value as? Listing {
            for obj in listing.children {
                if let link = obj as? Link {
                    self.links.append(link)
                }
            }
            self.paginator = listing.paginator
        }
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.tableView.reloadData()
            self.loading = false
        })
    }
})

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 let .Failure:
        println("Could not get access token from reddit.com.")
    case let .Success:
        if let token:OAuth2Token = result.value {
            self.session = Session(token: token)
        }
    }
}))

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 test reddift, you have to create another “Script” type application(personal use script) at reddit.com.

userscript

2. Build libraries

Test depends on Quick and Nimble. You may build them using Carthage ver easy. You could install and setup Carthage using Installer or Homebrew. reddift include Cartfile for Carthage. So, you build it with the following command.

> carthage update

3. 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"
}

Dependency

License

MIT License.